Docs / The Basics / HTTP Responses
HTTP Responses
Creating Responses
Strings and Arrays
All routes and controllers should return a response to be sent back to the user's browser. Laraflare provides several different ways to return responses. The most basic response is returning a string from a route or controller. The framework will automatically convert the string into a full HTTP response:
import { Route } from '@laraflare/framework';
Route.get('/', () => 'Hello World');
In addition to returning strings from your routes and controllers, you may also return arrays. The framework will automatically convert the array into a JSON response:
Route.get('/', () => [1, 2, 3]);
Note
Did you know you can also return Eloquent collections from your routes or controllers? They will automatically be converted to JSON. Give it a shot!
Response Objects
Typically, you won't just be returning simple strings or arrays from your route actions. Instead, you will be returning full Response instances.
Returning a full Response instance allows you to customize the response's HTTP status code and headers. The Response class (exported as HttpResponse) provides a variety of methods for building HTTP responses, and it is sent as a Fetch API Response:
import { Route, response } from '@laraflare/framework';
Route.get('/home', () => {
return response('Hello World', 200)
.header('Content-Type', 'text/plain');
});
Eloquent Models and Collections
You may also return Eloquent ORM models and collections directly from your routes and controllers. When you do, Laraflare will automatically convert the models and collections to JSON responses while respecting the model's hidden attributes:
import { Route } from '@laraflare/framework';
import { User } from '../app/Models/User';
Route.get('/user/{user}', (user: User) => user);
Attaching Headers to Responses
Keep in mind that most response methods are chainable, allowing for the fluent construction of response instances. For example, you may use the header method to add a series of headers to the response before sending it back to the user:
return response(content)
.header('Content-Type', type)
.header('X-Header-One', 'Header Value')
.header('X-Header-Two', 'Header Value');
Or, you may use the withHeaders method to specify an object of headers to be added to the response:
return response(content)
.withHeaders({
'Content-Type': type,
'X-Header-One': 'Header Value',
'X-Header-Two': 'Header Value',
});
You can remove specific headers from an outgoing response using the withoutHeader method:
return response(content).withoutHeader('X-Debug');
return response(content).withoutHeader(['X-Debug', 'X-Powered-By']);
Cache Control Middleware
Laraflare includes a cache.headers middleware, which may be used to quickly set the Cache-Control header for a group of routes. Directives should be provided using the "snake case" equivalent of the corresponding cache-control directive and should be separated by a semicolon. If etag is specified in the list of directives, a hash of the response content will automatically be set as the ETag identifier:
Route.middleware('cache.headers:public;max_age=30;s_maxage=300;stale_while_revalidate=600;etag').group(() => {
Route.get('/privacy', () => {
// ...
});
Route.get('/terms', () => {
// ...
});
});
Attaching Cookies to Responses
You may attach a cookie to an outgoing Response instance using the cookie method. You should pass the name, value, and the number of minutes the cookie should be considered valid to this method:
return response('Hello World').cookie(
'name', 'value', minutes
);
The cookie method also accepts a few more arguments which are used less frequently. Generally, these arguments have the same purpose and meaning as the attributes of a Set-Cookie header:
return response('Hello World').cookie(
'name', 'value', minutes, path, domain, secure, httpOnly
);
If you would like to ensure that a cookie is sent with the outgoing response but you do not yet have an instance of that response, you can use the Cookie facade to "queue" cookies for attachment to the response when it is sent. The queue method accepts the arguments needed to create a cookie instance. These cookies will be attached to the outgoing response before it is sent to the browser:
import { Cookie } from '@laraflare/framework';
Cookie.queue('name', 'value', minutes);
Generating Cookie Instances
If you would like to generate a Cookie instance that can be attached to a response instance at a later time, you may use the global cookie helper. This cookie will not be sent back to the client unless it is attached to a response instance:
import { cookie, response } from '@laraflare/framework';
const nameCookie = cookie('name', 'value', minutes);
return response('Hello World').cookie(nameCookie);
Expiring Cookies Early
You may remove a cookie by expiring it via the withoutCookie or withoutCookies method of an outgoing response:
return response('Hello World').withoutCookie('name');
return response('Hello World').withoutCookies([
'name',
'email',
'preferences',
]);
If you do not yet have an instance of the outgoing response, you may use the Cookie facade's expire method to expire a cookie:
Cookie.expire('name');
Cookies and Encryption
By default, all cookies generated by Laraflare are encrypted and signed so that they can't be modified or read by the client. If you would like to disable encryption for a subset of cookies generated by your application, you may use the encryptCookies method in your application's bootstrap/app.ts file:
.withMiddleware((middleware) => {
middleware.encryptCookies(['cookie_name']);
})
Note
In general, cookie encryption should never be disabled, as this exposes your cookies to potential client-side data exposure and tampering.
Redirects
Redirect responses are instances of the RedirectResponse class, and contain the proper headers needed to redirect the user to another URL. There are several ways to generate a RedirectResponse instance. The simplest method is to use the global redirect helper:
Route.get('/dashboard', () => redirect('/home/dashboard'));
Sometimes you may wish to redirect the user to their previous location, such as when a submitted form is invalid. You may do so by using the global back helper function. Since this feature utilizes the session, make sure the route calling the back function is using the web middleware group:
Route.post('/user/profile', () => {
// Validate the request...
return back().withInput();
});
Redirecting to Named Routes
When you call the redirect helper with no parameters, an instance of Redirector is returned, allowing you to call any method on the Redirector instance. For example, to generate a RedirectResponse to a named route, you may use the route method:
return redirect().route('login');
If your route has parameters, you may pass them as the second argument to the route method:
// For a route with the following URI: /profile/{id}
return redirect().route('profile', { id: 1 });
Populating Parameters via Eloquent Models
If you are redirecting to a route with an "ID" parameter that is being populated from an Eloquent model, you may pass the model itself. The ID will be extracted automatically:
// For a route with the following URI: /profile/{id}
return redirect().route('profile', [user]);
If you would like to customize the value that is placed in the route parameter, you can specify the column in the route parameter definition (/profile/{id:slug}) or you can override the getRouteKey method on your Eloquent model:
/**
* Get the value of the model's route key.
*/
override getRouteKey(): unknown {
return this.slug;
}
Redirecting to Controller Actions
You may also generate redirects to controller actions. To do so, pass the controller and action name to the action method:
import { UserController } from '../app/Http/Controllers/UserController';
return redirect().action([UserController, 'index']);
If your controller route requires parameters, you may pass them as the second argument to the action method:
return redirect().action(
[UserController, 'profile'], { id: 1 }
);
Redirecting to External Domains
Sometimes you may need to redirect to a domain outside of your application. You may do so by calling the away method, which creates a RedirectResponse without any additional URL encoding, validation, or verification:
return redirect().away('https://www.google.com');
Redirecting With Flashed Session Data
Redirecting to a new URL and flashing data to the session are usually done at the same time. Typically, this is done after successfully performing an action when you flash a success message to the session. For convenience, you may create a RedirectResponse instance and flash data to the session in a single, fluent method chain:
Route.post('/user/profile', () => {
// ...
return redirect('/dashboard').with('status', 'Profile updated!');
});
After the user is redirected, you may read the flashed message from the session and pass it to your Vue screen as a prop.
Redirecting With Input
You may use the withInput method provided by the RedirectResponse instance to flash the current request's input data to the session before redirecting the user to a new location. This is typically done if the user has encountered a validation error. Once the input has been flashed to the session, you may easily retrieve it during the next request to repopulate the form:
return back().withInput();
Other Response Types
The response helper may be used to generate other types of response instances. When the response helper is called without arguments, a ResponseFactory instance is returned. It provides several helpful methods for generating responses.
View Responses
Laraflare's screens are Vue components (resources/js), not server-rendered views, so a route returns the props a screen reads instead of a rendered view. If you need control over the response's status and headers, build the response with response and chain the header method.
JSON Responses
The json method will automatically set the Content-Type header to application/json, as well as convert the given value to JSON:
return response().json({
name: 'Abigail',
state: 'CA',
});
If you would like to create a JSONP response, you may use the json method in combination with the withCallback method:
return response()
.json({ name: 'Abigail', state: 'CA' })
.withCallback(request.input('callback'));
Markdown Responses
The markdown method may be used to return Markdown content with the Content-Type header set to text/markdown:
return response().markdown('# Hello\n\nWorld');
You may pass a custom HTTP status code and an object of additional headers as the second and third arguments:
return response().markdown('# Not Found', 404, { 'X-Custom-Header': 'Value' });
File Downloads
The download method may be used to generate a response that forces the user's browser to download the given file. The download method accepts a filename as the second argument to the method, which will determine the filename that is seen by the user downloading the file. Finally, you may pass an object of HTTP headers as the third argument to the method. The file may be a path, a Blob, bytes or a stream:
return response().download(file);
return response().download(file, name, headers);
Note
A Worker has no file system, so a path can only be read where Laraflare runs on Node (such as
npx artisan). In a Worker, givedownloadaBlob, bytes or a stream, such as an object read from R2.
File Responses
The file method may be used to display a file, such as an image or PDF, directly in the user's browser instead of initiating a download. This method accepts the file (a path, a Blob, bytes or a stream) as its first argument and an object of headers as its second argument:
return response().file(file);
return response().file(file, headers);
Streamed Responses
By streaming data to the client as it is generated, you can significantly reduce memory usage and improve performance, especially for very large responses. Streamed responses allow the client to begin processing data before the server has finished sending it. The callback given to the stream method receives a write function:
Route.get('/stream', () => {
return response().stream(async (write) => {
for (const string of ['developer', 'admin']) {
write(string);
await new Promise((resolve) => setTimeout(resolve, 2000)); // Simulate delay between chunks...
}
}, 200, { 'X-Accel-Buffering': 'no' });
});
For convenience, you may instead give the stream method an async generator or any iterable. Laraflare will send each value it yields as a chunk:
Route.post('/chat', () => {
return response().stream((async function* () {
for await (const chunk of upstream()) {
yield chunk;
}
})());
});
Streamed JSON Responses
If you need to stream JSON data incrementally, you may utilize the streamJson method. This method is especially useful for large datasets that need to be sent progressively to the browser in a format that can be easily parsed by JavaScript. Any iterable or async iterable in the data is sent item by item:
Route.get('/users.json', () => {
return response().streamJson({
users: userRows(),
});
});
Event Streams (SSE)
The eventStream method may be used to return a server-sent events (SSE) streamed response using the text/event-stream content type. The eventStream method accepts a generator function which should yield responses to the stream as the responses become available:
Route.get('/chat', () => {
return response().eventStream(async function* () {
for await (const chunk of upstream()) {
yield chunk;
}
});
});
If you would like to customize the name of the event, you may yield an instance of the StreamedEvent class:
import { StreamedEvent } from '@laraflare/framework';
yield new StreamedEvent('update', chunk);
Event streams may be consumed via an EventSource object by your application's frontend. The eventStream method will automatically send a </stream> update to the event stream when the stream is complete:
const source = new EventSource('/chat');
source.addEventListener('update', (event) => {
if (event.data === '</stream>') {
source.close();
return;
}
console.log(event.data);
});
To customize the final event that is sent to the event stream, you may provide a StreamedEvent instance to the eventStream method's endStreamWith argument (its third argument, after the headers):
return response().eventStream(async function* () {
// ...
}, {}, new StreamedEvent('update', '</stream>'));
Streamed Downloads
Sometimes you may wish to turn the string response of a given operation into a downloadable response without having to write the contents of the operation to disk. You may use the streamDownload method in this scenario. This method accepts a callback, filename, and an optional object of headers as its arguments:
return response().streamDownload(async (write) => {
write(await readme());
}, 'readme.md');
Response Macros
If you would like to define a custom response that you can re-use in a variety of your routes and controllers, you may use the macro method on the Response facade. Typically, you should call this method from the boot method of one of your application's service providers, such as the AppServiceProvider service provider:
import { Response, ServiceProvider } from '@laraflare/framework';
export class AppServiceProvider extends ServiceProvider {
/**
* Bootstrap any application services.
*/
override boot(): void {
Response.macro('caps', (value: string) => {
return Response.make(value.toUpperCase());
});
}
}
The macro function accepts a name as its first argument and a function as its second argument. The macro's function will be executed when calling the macro name from a ResponseFactory instance or the response helper:
return response().caps('foo');