← Back to blog

How to modify http responses in Laravel

| Laravel

Laravel middleware provides a convenient mechanism for inspecting and filtering HTTP requests entering your application.

Learn more about Laravel middleware

Additionally, middleware can be used to modify the HTTP response.

Here is how to do it.

Create a new middleware:

php artisan make:middleware MyMiddleware

Open up app/Http/Kernel.php file and add the newly created middleware in the $middleware key:

class Kernel
{
    protected $middleware = [
        // ...
        App\Http\Middleware\MyMiddleware::class,
    ];
}

Go back to the MyMiddleware file. Here you can modify the response:

public function handle(Request $request, Closure $next)
{
    /** @var \Illuminate\Http\Response $response */
    $response = $next($request);

    // Modify the response ...

    return $response;
}

For example, you can add a new HTTP header:

$response->addHeader($response->header('X-ADMIN', Auth::user()->isAdmin);

You can also change the status code based on a certain criteria:

if (false) {
	$response->setStatusCode(400);
}

Inspect the Illuminate\Http\Response for more methods.

Summary

  • Middleware modifies responses -- by calling $next($request) first, you get access to the response object and can modify headers, status codes, or content before it reaches the client.
  • Use Illuminate\Http\Response methods -- addHeader(), setStatusCode(), and other methods on the response object give you full control over what gets sent back.
Share