Mastering Laravel HTTP Response

aravel Laravel Views & Blade Templates – Beginner’s Guide

Laravel HTTP Responses Tutorial

In any web application, HTTP responses are what your server sends back to the client’s browser after handling a request. Laravel provides a rich and elegant API to build responses — from simple strings to JSON, file downloads, redirects, and even real-time streams.

In this tutorial, we’ll cover all the key concepts and features of HTTP responses in Laravel.


Creating Responses

Strings

The simplest type of response is just a string. Laravel automatically wraps it into a full HTTP response:

Route::get('/', function () {
    return 'Hello World';
});
Arrays → JSON

If you return an array, Laravel converts it to a JSON response:

Route::get('/', function () {
    return [1, 2, 3];
});
Eloquent Collections

You can even return Eloquent models or collections directly — they’ll be converted to JSON automatically:

use App\Models\User;

Route::get('/users', function () {
    return User::all();
});

Response Objects

For more control (status codes, headers, etc.), use the response() helper:

Route::get('/home', function () {
    return response('Hello World', 200)
        ->header('Content-Type', 'text/plain');
});

This returns a full Illuminate\Http\Response instance.


Attaching Headers

Responses can be customized with headers.

Using header() chain:
return response('Content')
    ->header('X-Custom', 'Value')
    ->header('Content-Type', 'application/json');
Using withHeaders():
return response('Content')->withHeaders([
    'X-Header-One' => 'One',
    'X-Header-Two' => 'Two',
]);

Cache Control Middleware

Laravel ships with cache.headers middleware to manage cache headers:

Route::middleware('cache.headers:public;max_age=2628000;etag')->group(function () {
    Route::get('/privacy', fn () => view('privacy'));
    Route::get('/terms', fn () => view('terms'));
});

Cookies in Responses

Attaching Cookies
return response('Hello')->cookie(
    'name', 'value', 60 // valid for 60 minutes
);
Queueing Cookies
use Illuminate\Support\Facades\Cookie;

Cookie::queue('name', 'value', 60);
Expiring Cookies
return response('Bye')->withoutCookie('name');

Cookie::expire('name'); // Without a response instance
Cookie Encryption

All cookies are encrypted by default. To exclude a cookie:

// bootstrap/app.php
->withMiddleware(function (Middleware $middleware) {
    $middleware->encryptCookies(except: ['cookie_name']);
})

Redirect Responses

Redirects use the Illuminate\Http\RedirectResponse class.

Basic Redirect
return redirect('/home');
Redirect Back
return back()->withInput();
Named Routes
return redirect()->route('profile', ['id' => 1]);
Controller Actions
return redirect()->action([UserController::class, 'index']);
External URLs
return redirect()->away('https://google.com');
With Flash Data
return redirect('/dashboard')->with('status', 'Profile updated!');

Other Response Types

View Responses
return response()->view('welcome', ['name' => 'John'], 200);

Or simply:

return view('welcome', ['name' => 'John']);
JSON Responses
return response()->json(['name' => 'Abigail', 'state' => 'CA']);

With JSONP:

return response()
    ->json(['name' => 'Abigail'])
    ->withCallback(request()->input('callback'));
File Downloads
return response()->download(storage_path('app/file.pdf'), 'custom.pdf');
Displaying Files
return response()->file(storage_path('app/image.png'));

Streamed Responses

Useful for sending large datasets or real-time updates.

Route::get('/stream', function () {
    return response()->stream(function () {
        echo "Chunk 1";
        flush();
        sleep(2);
        echo "Chunk 2";
    });
});
Streamed JSON
Route::get('/users.json', function () {
    return response()->streamJson([
        'users' => User::cursor(),
    ]);
});
Event Streams (SSE)
Route::get('/chat', function () {
    return response()->eventStream(function () {
        yield "data: Hello\n\n";
        yield "data: World\n\n";
    });
});
Streamed Downloads
return response()->streamDownload(function () {
    echo "Generated on the fly!";
}, 'output.txt');

Response Macros

Define reusable response types:

use Illuminate\Support\Facades\Response;

Response::macro('caps', function ($value) {
    return Response::make(strtoupper($value));
});

// Usage
return response()->caps('hello');

Important

Laravel’s HTTP response system is flexible and powerful. You can:

  • Return simple strings, arrays, JSON, and views
  • Customize headers, cookies, and cache
  • Redirect users (with flash data and inputs)
  • Stream large responses, files, and events
  • Extend responses with macros

This makes Laravel responses suitable for everything — from simple APIs to real-time applications.