Skip to main content
Version: CANARY 🚧

HTTP Requests

Introduction​

An HTTP request is the message the user sends to the Bow application through their browser or other tools such as curl, httpie, etc.

This message is handled by Bow via the Bow\Http\Request class. This class provides access to the request information: IP address, HTTP method, form data, uploaded files, etc.

Accessing the request​

Via the helper​

$request = request();
$name = $request->get('name');

Via dependency injection​

routes/app.php
use Bow\Http\Request;

$app->get('/', function (Request $request) {
return $request->get('name');
});

Via a controller​

namespace App\Controllers;

use App\Models\User;
use Bow\Http\Request;

class UserController
{
public function show(Request $request, int $id)
{
$user = User::retrieve($id);
$user->name = $request->get('name');
$user->persist();

return view('user/profile', ['user' => $user]);
}
}

Retrieving data​

Retrieving a value​

// Via the get() method
$name = $request->get('name');

// Via the magic property
$name = $request->name;

// With a default value
$name = $request->get('name', 'InvitΓ©');

// With a default callback
$name = $request->get('name', fn() => User::first()->name);

Retrieving all data​

$data = $request->all();

Data by source: query string vs POST​

When you want to explicitly read $_GET or $_POST (instead of the merged array returned by all()), use query() and post():

// Full $_GET array
$queryParams = $request->query();

// A specific $_GET key (returns [] if absent)
$page = $request->query('page');

// Full $_POST array
$body = $request->post();

// A specific $_POST key
$name = $request->post('name');
When should you prefer get()?

get($key) first looks in the merged routes/query/body and offers a default fallback (get('name', 'InvitΓ©')). Reserve query() / post() for cases where the origin of the data matters (e.g. never reading ?admin=1 from the URL).

JSON and PUT bodies​

Bow automatically decodes the request body: if the Content-Type header is application/json, the JSON is decoded and merged into the data accessible via get(), all() and post(). No manual step is required to consume a JSON API:

// POST request with Content-Type: application/json and body {"name": "Franck"}
$name = $request->get('name'); // "Franck"
$body = $request->post(); // ['name' => 'Franck']

PUT request bodies (form-urlencoded) are also parsed automatically and available through the same methods.

Invalid JSON

If the Content-Type is application/json but the body is not valid JSON, Bow throws a Bow\Http\Exception\BadRequestException.

Filtering data​

// Retrieve only certain fields
$data = $request->only(['name', 'email']);

// Exclude certain fields
$data = $request->ignore(['password', 'password_confirmation']);

// Both also accept a list of arguments
$data = $request->only('name', 'email');
$data = $request->ignore('password', 'password_confirmation');

Checking existence​

if ($request->has('name')) {
// The field exists
}

Retrieving old values​

After a redirect with validation errors:

$oldName = $request->old('name', 'Valeur par dΓ©faut');

Uploaded files​

Retrieving a file​

$file = $request->file('avatar');

if ($file) {
$file->moveTo('/uploads/avatars');
}

Multiple files​

$files = $request->file('documents');

foreach ($files as $file) {
$file->moveTo('/uploads/documents/' . $file->getClientFilename());
}

Checking existence​

if (Request::hasFile('avatar')) {
// A file was uploaded
}

Request information​

URL and path​

// Request path (e.g. /users/1)
$path = $request->path();

// Full URL (e.g. https://example.com/users/1)
$url = $request->url();

// Origin (e.g. https://example.com)
$origin = $request->origin();

// Hostname (e.g. example.com)
$host = $request->hostname();

// Domain without port (e.g. example.com)
$domain = $request->domain();

Checking the path​

if ($request->is('users/*')) {
// The request starts with /users/
}

HTTP method​

$method = $request->method(); // GET, POST, PUT, DELETE, etc.

// Quick checks
if ($request->isGet()) { }
if ($request->isPost()) { }
if ($request->isPut()) { }
if ($request->isDelete()) { }

Request type​

// AJAX request
if ($request->isAjax()) {
// AJAX handling
}

// Request expecting JSON
if ($request->wantsJson()) {
return response()->json($data);
}

Client information​

IP address and port​

$ip = $request->ip();
$port = $request->port();

User Agent​

$userAgent = $request->userAgent();

Language and locale​

$lang = $request->lang();     // e.g. "fr"
$locale = $request->locale(); // e.g. "fr_FR"

Referer​

$referer = $request->referer();

if ($request->isReferer('https://google.com/*')) {
// The user comes from Google
}

Protocol and security​

$protocol = $request->protocol(); // http or https

if ($request->isSecure()) {
// HTTPS connection
}

if ($request->isProtocol('https')) {
// Same thing
}

HTTP headers​

Retrieving a header​

$contentType = $request->getHeader('content-type');
$authorization = $request->getHeader('authorization');

Retrieving all headers​

$headers = $request->getHeaders();

Checking existence​

if ($request->hasHeader('x-api-key')) {
$apiKey = $request->getHeader('x-api-key');
}

Request identifier​

Each request has a unique identifier:

$requestId = $request->id();
// or
$requestId = $request->getId();

// Set a custom ID
$request->setId('custom-request-id');

Session and authentication​

Accessing the session​

$session = $request->session();
$session->put('key', 'value');

Authenticated user​

$user = $request->user();

// With a specific guard
$user = $request->user('api');

Cookies​

// Retrieve all cookies
$cookies = $request->cookie();

// Retrieve a specific cookie
$token = $request->cookie('remember_token');

Validation​

Validate data directly from the request:

$validation = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|email',
'password' => 'required|min:8'
]);

if ($validation->fails()) {
return back()->withErrors($validation->getMessages());
}

Bags (shared data)​

Bags let you store values within a single request (for example permissions resolved by a middleware, which a controller will read later) without polluting the inputs.

// Set / read a value
$request->setBag('user_permissions', ['read', 'write']);
$permissions = $request->getBag('user_permissions');

// Read / replace the entire bags array
$all = $request->getBags();
$request->setBags(['user_permissions' => ['read'], 'feature_flags' => ['v2']]);

Request time​

$timestamp = $request->time();

Summary table​

MethodDescription
get($key, $default)Retrieves a value (all sources merged)
query($key = null)Query string parameters ($_GET)
post($key = null)POST body data ($_POST)
all()All data
only($keys)Filter by keys
ignore($keys)Exclude keys
has($key)Check existence
file($key)Retrieve a file
path()Request path
url()Full URL
method()HTTP method
ip()Client IP address
getHeader($key)HTTP header
session()Session instance
user($guard)Authenticated user
validate($rules)Validate data
setBag($name, $value) / getBag($name)Shared data within the request

Is something missing?

If you run into problems with the documentation or have suggestions to improve the documentation or the project in general, please open an issue for us, or send a tweet mentioning the Twitter account @bowframework or directly on github.