Creating Responses in Laravel: Strings, Arrays, Response Objects, Headers, Cookies, Redirects, and More
This guide explains how Laravel handles HTTP responses, covering simple string and array returns, full Response objects, adding headers and cookies, cache‑control middleware, various redirect techniques, view and JSON responses, file downloads, stream downloads, and custom response macros.
Creating Responses
After a route or controller finishes its business logic, Laravel automatically converts the returned value into a full HTTP response sent to the browser.
String & Array
The simplest response is a plain string; Laravel wraps it in an HTTP response automatically:
Route::get('/', function () {
return 'Hello World';
});You can also return an array, which Laravel converts to a JSON response:
Route::get('/', function () {
return [1, 2, 3];
});Tip: Returning an Eloquent collection works the same way—it will be transformed into JSON.
Response Object
In most cases you will return an Illuminate\Http\Response instance (or a view) to customise status codes and headers. The Response class extends Symfony\Component\HttpFoundation\Response , giving you many methods to build HTTP responses:
Route::get('home', function () {
return response('Hello World', 200)
->header('Content-Type', 'text/plain');
});Adding Response Headers
Response methods are chainable, allowing you to add multiple headers fluently:
return response($content)
->header('Content-Type', $type)
->header('X-Header-One', 'Header Value')
->header('X-Header-Two', 'Header Value');Or use withHeaders to pass an associative array:
return response($content)
->withHeaders([
'Content-Type' => $type,
'X-Header-One' => 'Header Value',
'X-Header-Two' => 'Header Value',
]);Cache‑Control Middleware
Laravel includes the cache.headers middleware for quickly setting Cache‑Control headers on a route group. If you specify etag , Laravel will automatically generate an ETag based on the MD5 hash of the response content:
Route::middleware('cache.headers:public;max_age=2628000;etag')
->group(function () {
Route::get('privacy', function () {
// ...
});
Route::get('terms', function () {
// ...
});
});Adding Cookies to a Response
You can attach cookies using the cookie method on a response instance:
return response($content)
->header('Content-Type', $type)
->cookie('name', 'value', $minutes);The cookie method accepts the same parameters as PHP's native setcookie function:
return response($content)
->cookie($name, $value, $minutes, $path, $domain, $secure, $httpOnly);Alternatively, you can use the Cookie facade's queue method to attach a cookie to the outgoing response:
Cookie::queue(Cookie::make('name', 'value', $minutes));
Cookie::queue('name', 'value', $minutes);Cookies & Encryption
By default, Laravel encrypts and signs all cookies. To exclude specific cookies from encryption, add their names to the $except array in App\Http\Middleware\EncryptCookies :
/**
* The names of the cookies that should not be encrypted.
*
* @var array
*/
protected $except = [
'cookie_name',
];Redirects
A redirect response is an instance of Illuminate\Http\RedirectResponse containing the necessary headers to send the user to another URL.
Simple Redirect
Route::get('dashboard', function () {
return redirect('home/dashboard');
});Redirect Back
Use back() to send the user to the previous location, typically after a validation failure. The route must be within the web middleware group (or any session middleware):
Route::post('user/profile', function () {
// Validate request...
return back()->withInput();
});Redirect to a Named Route
return redirect()->route('login');
// With parameters
return redirect()->route('profile', ['id' => 1]);Redirect to a Controller Action
return redirect()->action('HomeController@index');
// With parameters
return redirect()->action('UserController@profile', ['id' => 1]);Redirect to an External URL
return redirect()->away('https://www.google.com');Redirect with Flash Session Data
It is common to flash data to the session when redirecting after a successful action:
Route::post('user/profile', function () {
// Update profile...
return redirect('dashboard')->with('status', 'Profile updated!');
});In the destination view you can display the flashed message:
@if (session('status'))
{{ session('status') }}
@endifOther Response Types
View Responses
Return a view while still controlling the status code and headers:
return response()
->view('hello', $data, 200)
->header('Content-Type', $type);For simple cases you can use the global view() helper.
JSON Responses
return response()->json([
'name' => 'Abigail',
'state' => 'CA',
]);For JSONP you can chain withCallback :
return response()->json([
'name' => 'Abigail',
'state' => 'CA',
])->withCallback($request->input('callback'));File Downloads
return response()->download($pathToFile);
return response()->download($pathToFile, $name, $headers);
return response()->download($pathToFile)->deleteFileAfterSend();Note: Symfony HttpFoundation requires an ASCII filename for downloads.
Stream Downloads
Generate a downloadable response from a string or callback without writing to disk:
return response()->streamDownload(function () {
echo GitHub::api('repo')
->contents()
->readme('laravel', 'laravel')['contents'];
}, 'laravel-readme.md');File Responses
Display a file (image, PDF, etc.) directly in the browser:
return response()->file($pathToFile);
return response()->file($pathToFile, $headers);Response Macros
You can define reusable custom responses using the Response facade's macro method, typically inside a service provider's boot method:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Response;
class ResponseMacroServiceProvider extends ServiceProvider
{
/**
* Register response macros.
*/
public function boot()
{
Response::macro('caps', function ($value) {
return Response::make(strtoupper($value));
});
}
}Use the macro like any other response method:
return response()->caps('foo');Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.