LaraflareDocsPackages13.x

Docs / The Basics / HTTP Requests

HTTP Requests

Introduction

Laraflare's Request class provides an object-oriented way to interact with the current HTTP request being handled by your application as well as retrieve the input, cookies, and files that were submitted with the request. It extends the Fetch API's Request, so everything a Worker's Request can do is available on it too.

Interacting With The Request

Accessing the Request

To obtain an instance of the current HTTP request, type the Request class on your route closure or controller method. The incoming request instance will automatically be passed in by the Laraflare service container:

import { redirect, type Request } from '@laraflare/framework';
import { Controller } from './Controller';

export class UserController extends Controller {
  /**
   * Store a new user.
   */
  store(request: Request) {
    const name = request.input('name');

    // Store the user...

    return redirect('/users');
  }
}

As mentioned, you may also type the Request class on a route closure. The incoming request will automatically be passed to the closure when it is executed:

import { Route, type Request } from '@laraflare/framework';

Route.get('/', (request: Request) => {
  // ...
});

Dependency Injection and Route Parameters

If your route has parameters, you may still read them from the request. For example, if your route is defined like so:

import { Route } from '@laraflare/framework';
import { UserController } from '../app/Http/Controllers/UserController';

Route.put('/user/{id}', [UserController, 'update']);

You may access your id route parameter with the request's route method:

import { redirect, type Request } from '@laraflare/framework';
import { Controller } from './Controller';

export class UserController extends Controller {
  /**
   * Update the specified user.
   */
  update(request: Request) {
    const id = request.route('id');

    // Update the user...

    return redirect('/users');
  }
}

Request Path, Host, and Method

The Request instance provides a variety of methods for examining the incoming HTTP request. We will discuss a few of the most important methods below.

Retrieving the Request Path

The path method returns the request's path information. So, if the incoming request is targeted at http://example.com/foo/bar, the path method will return foo/bar:

const uri = request.path();

Inspecting the Request Path / Route

The is method allows you to verify that the incoming request path matches a given pattern. You may use the * character as a wildcard when utilizing this method:

if (request.is('admin/*')) {
  // ...
}

Using the routeIs method, you may determine if the incoming request has matched a named route:

if (request.routeIs('admin.*')) {
  // ...
}

Retrieving the Request URL

To retrieve the full URL for the incoming request you may use the urlWithoutQuery or fullUrl methods. The urlWithoutQuery method will return the URL without the query string, while the fullUrl method includes the query string. (The url property is the Fetch API's, and is always the full URL.)

const url = request.urlWithoutQuery();

const urlWithQueryString = request.fullUrl();

If you would like to append query string data to the current URL, you may call the fullUrlWithQuery method. This method merges the given object of query string variables with the current query string:

request.fullUrlWithQuery({ type: 'phone' });

If you would like to get the current URL without a given query string parameter, you may utilize the fullUrlWithoutQuery method:

request.fullUrlWithoutQuery(['type']);

Retrieving the Request Host

You may retrieve the "host" of the incoming request via the host, httpHost, and schemeAndHttpHost methods:

// http://localhost:8000
request.host(); // localhost
request.httpHost(); // localhost:8000
request.schemeAndHttpHost(); // http://localhost:8000

Retrieving the Request Method

The method property holds the HTTP verb for the request. You may use the isMethod method to verify that the HTTP verb matches a given string:

const method = request.method;

if (request.isMethod('post')) {
  // ...
}

Request Headers

You may retrieve a request header from the Request instance using the header method. If the header is not present on the request, undefined will be returned. However, the header method accepts an optional second argument that will be returned if the header is not present on the request:

const value = request.header('X-Header-Name');

const value = request.header('X-Header-Name', 'default');

The hasHeader method may be used to determine if the request contains a given header:

if (request.hasHeader('X-Header-Name')) {
  // ...
}

For convenience, the bearerToken method may be used to retrieve a bearer token from the Authorization header. If no token is present, undefined will be returned:

const token = request.bearerToken();

Request IP Address

The ip method may be used to retrieve the IP address of the client that made the request to your application:

const ipAddress = request.ip();

If you would like to retrieve an array of IP addresses, including all of the client IP addresses that were forwarded by proxies, you may use the ips method. The "original" client IP address will be at the end of the array:

const ipAddresses = request.ips();

In general, IP addresses should be considered untrusted, user-controlled input and be used for informational purposes only.

Content Negotiation

Laraflare provides several methods for inspecting the incoming request's requested content types via the Accept header. First, the getAcceptableContentTypes method will return an array containing all of the content types accepted by the request:

const contentTypes = request.getAcceptableContentTypes();

The accepts method accepts an array of content types and returns true if any of the content types are accepted by the request. Otherwise, false will be returned:

if (request.accepts(['text/html', 'application/json'])) {
  // ...
}

You may use the prefers method to determine which content type out of a given array of content types is most preferred by the request. If none of the provided content types are accepted by the request, null will be returned:

const preferred = request.prefers(['text/html', 'application/json']);

Since many applications only serve HTML or JSON, you may use the expectsJson method to quickly determine if the incoming request expects a JSON response:

if (request.expectsJson()) {
  // ...
}

If you need to determine whether the request specifically prefers Markdown or will accept Markdown among other content types, such as when serving AI agents or other clients that consume Markdown responses, you may use the wantsMarkdown and acceptsMarkdown methods:

if (request.wantsMarkdown()) {
  // The client's most preferred content type is text/markdown...
}

if (request.acceptsMarkdown()) {
  // The client accepts Markdown responses...
}

Input

Retrieving Input

Retrieving All Input Data

You may retrieve all of the incoming request's input data as an object using the all method. This method may be used regardless of whether the incoming request is from an HTML form or is an XHR request:

const input = request.all();

Using the collect method, you may retrieve all of the incoming request's input data as a collection:

const input = request.collect();

The collect method also allows you to retrieve a subset of the incoming request's input as a collection:

request.collect('users').each((user: string) => {
  // ...
});

Retrieving an Input Value

Using a few simple methods, you may access all of the user input from your Request instance without worrying about which HTTP verb was used for the request. Regardless of the HTTP verb, the input method may be used to retrieve user input:

const name = request.input('name');

You may pass a default value as the second argument to the input method. This value will be returned if the requested input value is not present on the request:

const name = request.input('name', 'Sally');

When working with forms that contain array inputs, use "dot" notation to access the arrays:

const name = request.input('products.0.name');

const names = request.input('products.*.name');

You may call the input method without any arguments in order to retrieve all of the input values as an object:

const input = request.input();

Retrieving Input From the Query String

While the input method retrieves values from the entire request payload (including the query string), the query method will only retrieve values from the query string:

const name = request.query('name');

If the requested query string value data is not present, the second argument to this method will be returned:

const name = request.query('name', 'Helen');

You may call the query method without any arguments in order to retrieve all of the query string values as an object:

const query = request.query();

Retrieving JSON Input Values

When sending JSON requests to your application, you may access the JSON data via the input method as long as the Content-Type header of the request is properly set to application/json. You may even use "dot" syntax to retrieve values that are nested within JSON arrays / objects:

const name = request.input('user.name');

Retrieving Stringable Input Values

Instead of retrieving the request's input data as a primitive string, you may use the string method to retrieve the request data as an instance of Stringable:

const name = request.string('name').trim();

Retrieving Integer Input Values

To retrieve input values as integers, you may use the integer method. This method will attempt to cast the input value to an integer. If the input is not present, it will return the default value you specify. This is particularly useful for pagination or other numeric inputs:

const perPage = request.integer('per_page');

Retrieving Boolean Input Values

When dealing with HTML elements like checkboxes, your application may receive "truthy" values that are actually strings. For example, "true" or "on". For convenience, you may use the boolean method to retrieve these values as booleans. The boolean method returns true for 1, "1", true, "true", "on", and "yes". All other values will return false:

const archived = request.boolean('archived');

Retrieving Input Values Strictly

The string, integer, float, and boolean methods cast whatever input they receive. For example, ?count=abc is cast to 0 by the integer method. If you would rather receive the default value when the input does not have the expected type, you may pass true as the last argument (strict) to these methods:

const count = request.integer('count', 5, true);

const price = request.float('price', 0, true);

const name = request.string('name', 'Guest', true);

const archived = request.boolean('archived', false, true);

When strict, the integer and float methods return the default unless the input is a valid integer or number, the string method returns the default unless the input is a string or a number, and the boolean method returns the default unless the input is one of 1, true, on, yes, 0, false, off, or no.

Retrieving Array Input Values

Input values containing arrays may be retrieved using the array method. This method will always cast the input value to an array. If the request does not contain an input value with the given name, an empty array will be returned:

const versions = request.array('versions');

Retrieving Date Input Values

For convenience, input values containing dates / times may be retrieved as Carbon instances using the date method. If the request does not contain an input value with the given name, null will be returned:

const birthday = request.date('birthday');

The second and third arguments accepted by the date method may be used to specify the date's format and timezone, respectively:

const elapsed = request.date('elapsed', '!H:i', 'Europe/Madrid');

If the input value is present but has an invalid format, an error will be thrown; therefore, it is recommended that you validate the input before invoking the date method.

Retrieving Interval Input Values

Input values containing durations may be retrieved as intervals using the interval method. If the request does not contain an input value with the given name, null will be returned:

const duration = request.interval('duration');

If the input value is numeric, you may provide a unit as the second argument, a string such as second, minute, or day:

const timeout = request.interval('timeout', 'second');

const delay = request.interval('delay', 'minute');

If the input value is present but has an invalid format, an error will be thrown; therefore, it is recommended that you validate the input before invoking the interval method.

Retrieving UUID and ULID Input Values

Input values containing UUIDs or ULIDs may be retrieved using the uuid and ulid methods, which return the value as a string. If the request does not contain an input value with the given name, null will be returned:

const orderId = request.uuid('order_id');

const eventId = request.ulid('event_id');

If the input value is present but is not a valid UUID or ULID, an error will be thrown; therefore, it is recommended that you validate the input before invoking these methods.

Retrieving Enum Input Values

Input values that correspond to backed enums may also be retrieved from the request. If the request does not contain an input value with the given name or the enum does not have a backing value that matches the input value, null will be returned. The enum method accepts the name of the input value and the enum as its first and second arguments:

import { Status } from '../app/Enums/Status';

const status = request.enum('status', Status);

You may also provide a default value that will be returned if the value is missing or invalid:

const status = request.enum('status', Status, Status.Pending);

If the input value is an array of values that correspond to an enum, you may use the enums method to retrieve the array of values as enum members:

import { Product } from '../app/Enums/Product';

const products = request.enums('products', Product);

Retrieving a Portion of the Input Data

If you need to retrieve a subset of the input data, you may use the only and except methods. Both of these methods accept a single array or a dynamic list of arguments:

const input = request.only(['username', 'password']);

const input = request.only('username', 'password');

const input = request.except(['credit_card']);

const input = request.except('credit_card');

Warning

The only method returns all of the key / value pairs that you request; however, it will not return key / value pairs that are not present on the request.

Input Presence

You may use the has method to determine if a value is present on the request. The has method returns true if the value is present on the request:

if (request.has('name')) {
  // ...
}

When given an array, the has method will determine if all of the specified values are present:

if (request.has(['name', 'email'])) {
  // ...
}

The hasAny method returns true if any of the specified values are present:

if (request.hasAny(['name', 'email'])) {
  // ...
}

The whenHas method will execute the given closure if a value is present on the request:

request.whenHas('name', (input: string) => {
  // ...
});

A second closure may be passed to the whenHas method that will be executed if the specified value is not present on the request:

request.whenHas('name', (input: string) => {
  // The "name" value is present...
}, () => {
  // The "name" value is not present...
});

If you would like to determine if a value is present on the request and is not an empty string, you may use the filled method:

if (request.filled('name')) {
  // ...
}

If you would like to determine if a value is missing from the request or is an empty string, you may use the isNotFilled method:

if (request.isNotFilled('name')) {
  // ...
}

When given an array, the isNotFilled method will determine if all of the specified values are missing or empty:

if (request.isNotFilled(['name', 'email'])) {
  // ...
}

The anyFilled method returns true if any of the specified values is not an empty string:

if (request.anyFilled(['name', 'email'])) {
  // ...
}

The whenFilled method will execute the given closure if a value is present on the request and is not an empty string:

request.whenFilled('name', (input: string) => {
  // ...
});

A second closure may be passed to the whenFilled method that will be executed if the specified value is not "filled":

request.whenFilled('name', (input: string) => {
  // The "name" value is filled...
}, () => {
  // The "name" value is not filled...
});

To determine if a given key is absent from the request, you may use the missing and whenMissing methods:

if (request.missing('name')) {
  // ...
}

request.whenMissing('name', () => {
  // The "name" value is missing...
}, () => {
  // The "name" value is present...
});

Merging Additional Input

Sometimes you may need to manually merge additional input into the request's existing input data. To accomplish this, you may use the merge method. If a given input key already exists on the request, it will be overwritten by the data provided to the merge method:

request.merge({ votes: 0 });

The mergeIfMissing method may be used to merge input into the request if the corresponding keys do not already exist within the request's input data:

request.mergeIfMissing({ votes: 0 });

Old Input

Laraflare allows you to keep input from one request during the next request. This feature is particularly useful for re-populating forms after detecting validation errors. However, if you are using Laraflare's included validation features, it is possible that you will not need to manually use these session input flashing methods directly, as some of Laraflare's built-in validation facilities will call them automatically.

Flashing Input to the Session

The flash method on the Request class will flash the current input to the session so that it is available during the user's next request to the application:

request.flash();

You may also use the flashOnly and flashExcept methods to flash a subset of the request data to the session. These methods are useful for keeping sensitive information such as passwords out of the session:

request.flashOnly(['username', 'email']);

request.flashExcept('password');

Flashing Input Then Redirecting

Since you often will want to flash input to the session and then redirect to the previous page, you may easily chain input flashing onto a redirect using the withInput method:

return redirect('/form').withInput();

return redirect().route('user.create').withInput();

return redirect('/form').withInput(
  request.except('password'),
);

Retrieving Old Input

To retrieve flashed input from the previous request, invoke the old method on an instance of Request. The old method will pull the previously flashed input data from the session:

const username = request.old('username');

Note

Laraflare's screens are Vue, not server-rendered templates, so there is no template old helper: pass the old input to the screen as a prop, and the Vue form reads it from there.

Cookies

Retrieving Cookies From Requests

All cookies created by the Laraflare framework are encrypted and signed with an authentication code, meaning they will be considered invalid if they have been changed by the client. To retrieve a cookie value from the request, use the cookie method on a Request instance:

const value = request.cookie('name');

Input Trimming and Normalization

By default, Laraflare includes the TrimStrings and ConvertEmptyStringsToNull middleware in your application's global middleware stack. These middleware will automatically trim all incoming string fields on the request, as well as convert any empty string fields to null. This allows you to not have to worry about these normalization concerns in your routes and controllers.

Disabling Input Normalization

If you would like to disable this behavior for all requests, you may remove the two middleware from your application's middleware stack by invoking the middleware.remove method in your application's bootstrap/app.ts file:

import { ConvertEmptyStringsToNull, TrimStrings } from '@laraflare/framework';

.withMiddleware((middleware) => {
  middleware.remove([
    ConvertEmptyStringsToNull,
    TrimStrings,
  ]);
})

If you would like to disable string trimming and empty string conversion for a subset of requests to your application, you may use the trimStrings and convertEmptyStringsToNull middleware methods within your application's bootstrap/app.ts file. Both methods accept an array of closures, which should return true or false to indicate whether input normalization should be skipped:

.withMiddleware((middleware) => {
  middleware.convertEmptyStringsToNull([
    (request: Request) => request.is('admin/*'),
  ]);

  middleware.trimStrings([
    (request: Request) => request.is('admin/*'),
  ]);
})

Files

Retrieving Uploaded Files

You may retrieve uploaded files from a Request instance using the file method. The file method returns an instance of the UploadedFile class, which provides a variety of methods for interacting with the file:

const file = request.file('photo');

You may determine if a file is present on the request using the hasFile method:

if (request.hasFile('photo')) {
  // ...
}

If the uploaded file is an image that you need to manipulate before storing, you may use the image method to retrieve an Image instance, or null if the file is not present:

const image = request.image('photo');

For more information on manipulating images, please consult the complete image manipulation documentation.

Validating Successful Uploads

In addition to checking if the file is present, you may verify that there were no problems uploading the file via the isValid method:

if (request.file('photo').isValid()) {
  // ...
}

File Paths and Extensions

The UploadedFile class also contains methods for accessing the file's name and its extension. On Workers an upload is held in memory rather than in a temporary file, so getPathname returns a synthetic path. The guessExtension method will attempt to guess the file's extension based on its type, while getClientOriginalExtension returns the extension that was supplied by the client; the two may differ:

const path = request.file('photo').getPathname();

const extension = request.file('photo').guessExtension();

Other File Methods

There are a variety of other methods available on UploadedFile instances, such as getClientOriginalName, getClientMimeType, getSize, get (the file's contents), arrayBuffer and stream. Check out the UploadedFile class in src/Illuminate/Http/UploadedFile.ts for the full list.

Storing Uploaded Files

To store an uploaded file, you will typically use one of your configured filesystems. The UploadedFile class has a store method that will move an uploaded file to one of your disks, which may be a location on your local filesystem or a cloud storage location like Cloudflare R2.

The store method accepts the path where the file should be stored relative to the filesystem's configured root directory. This path should not contain a filename, since a unique ID will automatically be generated to serve as the filename.

The store method also accepts an optional second argument for the name of the disk that should be used to store the file. The method returns a promise of the path of the file relative to the disk's root:

const path = await request.file('photo').store('images');

const path = await request.file('photo').store('images', 'r2');

If you do not want a filename to be automatically generated, you may use the storeAs method, which accepts the path, filename, and disk name as its arguments:

const path = await request.file('photo').storeAs('images', 'filename.jpg');

const path = await request.file('photo').storeAs('images', 'filename.jpg', 'r2');

Note

For more information about file storage in Laraflare, check out the complete file storage documentation.

Configuring Trusted Proxies

When running your applications behind a load balancer that terminates TLS / SSL certificates, you may notice your application sometimes does not generate HTTPS links when using the url helper. Typically this is because your application is being forwarded traffic from your load balancer on port 80 and does not know it should generate secure links.

To solve this, you may enable the TrustProxies middleware that is included in your Laraflare application, which allows you to quickly customize the load balancers or proxies that should be trusted by your application. Your trusted proxies should be specified using the trustProxies middleware method in your application's bootstrap/app.ts file:

.withMiddleware((middleware) => {
  middleware.trustProxies(['192.168.1.1', '10.0.0.0/8']);
})

In addition to configuring the trusted proxies, you may also configure the proxy headers that should be trusted:

import { Request } from '@laraflare/framework';

.withMiddleware((middleware) => {
  middleware.trustProxies(null,
    Request.HEADER_X_FORWARDED_FOR |
    Request.HEADER_X_FORWARDED_HOST |
    Request.HEADER_X_FORWARDED_PORT |
    Request.HEADER_X_FORWARDED_PROTO |
    Request.HEADER_X_FORWARDED_AWS_ELB,
  );
})

Note

If you are using AWS Elastic Load Balancing, the headers value should be Request.HEADER_X_FORWARDED_AWS_ELB. If your load balancer uses the standard Forwarded header from RFC 7239, the headers value should be Request.HEADER_FORWARDED.

Trusting All Proxies

If you are using a "cloud" load balancer provider, you may not know the IP addresses of your actual balancers. In this case, you may use * to trust all proxies:

.withMiddleware((middleware) => {
  middleware.trustProxies('*');
})

Configuring Trusted Hosts

By default, Laraflare will respond to all requests it receives regardless of the content of the HTTP request's Host header. In addition, the Host header's value will be used when generating absolute URLs to your application during a web request.

Typically, you should configure your web server or Cloudflare route to only send requests to your application that match a given hostname. However, if you do not have the ability to do that and need to instruct Laraflare to only respond to certain hostnames, you may do so by enabling the TrustHosts middleware for your application.

To enable the TrustHosts middleware, you should invoke the trustHosts middleware method in your application's bootstrap/app.ts file. Using the first argument of this method, you may specify the hostnames that your application should respond to. The hostname string is treated as a regular expression. Incoming requests with other Host headers will be rejected:

.withMiddleware((middleware) => {
  middleware.trustHosts(['^example\\.test$']);
})

By default, requests coming from subdomains of the application's URL are also automatically trusted. If you would like to disable this behavior, you may pass false as the second argument:

.withMiddleware((middleware) => {
  middleware.trustHosts(['^example\\.test$'], false);
})

If you need to access your application's configuration files to determine your trusted hosts, you may provide a closure as the first argument:

.withMiddleware((middleware) => {
  middleware.trustHosts(() => [config('app.trusted_hosts')]);
})
Adapted from Laravel's documentation, Copyright (c) Taylor Otwell, used under the MIT License.