Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 67 ยท Routing and Controllers

Requests and Responses

Read input, files, headers and JSON from the Laravel Request, then return strings, views, JSON, redirects, cookies and downloads, with runnable Request and Response stand-ins.

Every web framework boils down to one function: it takes a request and returns a response. Laravel wraps both in objects. The request (Illuminate\Http\Request) gives you tidy access to everything the browser sent: form fields, query string, uploaded files, headers, cookies and JSON bodies. The response carries what goes back: a status code, headers and a body. Your controllers and closures sit in the middle.

PHP gives you raw superglobals such as $_GET, $_POST and $_SERVER for the same job; the HTTP headers and redirects lesson shows that raw view. Laravel's objects replace them with something testable, consistent and safe to pass around. This lesson covers the everyday API, and then you will build small stand-ins for both objects in plain PHP so you can see how little magic is involved.

Laravel code below is read-only. The runnable examples are plain-PHP imitations of the same ideas, not the real classes.

Getting the request

Type-hint Request in a closure or controller method and the container supplies it (see controllers):

PHP
use Illuminate\Http\Request;

Route::post('/profile', function (Request $request) {
    $name = $request->input('name');
    // ...
});

Inside a view or helper code the global request() function returns the current one, but prefer injection: it is explicit and easier to test.

Reading input

The request unifies query string and body, so you do not care whether a value came from ?page=2 or from a form field:

PHP
$request->input('name');                 // from body or query string
$request->input('name', 'Guest');        // with a default
$request->input('user.email');           // dot notation reaches into nested data and JSON
$request->query('page', 1);              // query string only
$request->all();                         // every input value as an array
$request->only(['name', 'email']);       // just those keys
$request->except(['password']);          // everything but those keys

$request->has('name');                   // key present (even if empty)
$request->filled('name');                // key present and not empty
$request->boolean('subscribe');          // "1", "true", "on", "yes" become true
$request->integer('per_page', 15);       // cast to int
$request->string('title')->trim();       // a fluent string object

There are two traps. First, input is untrusted. A form field called is_admin can be sent by anyone, so never pass $request->all() to a model; validate it first (see validation). Second, has() is true for an empty string while filled() is not; use the one that matches your intent.

A request with Content-Type: application/json has its body decoded automatically, so $request->input('user.name') works for {"user": {"name": "Ada"}} too.

Files, headers and request details

PHP
$request->file('avatar');                // an UploadedFile or null
$request->hasFile('avatar');             // true when a file was uploaded
$request->header('Accept-Language');     // case-insensitive header lookup
$request->bearerToken();                 // token from "Authorization: Bearer ..."
$request->cookie('theme');               // a decrypted cookie value

$request->method();                      // "POST"
$request->isMethod('post');              // true
$request->path();                        // "posts/42" (no leading slash)
$request->url();                         // full URL without the query string
$request->fullUrl();                     // with the query string
$request->is('admin/*');                 // does the path match a pattern?
$request->routeIs('posts.*');            // does the route name match?
$request->ip();                          // client IP address
$request->expectsJson();                 // does the client want JSON back?

Uploads get their own treatment in file uploads and storage. expectsJson() is how Laravel decides between an HTML error page and a JSON error, which matters when you build APIs.

Returning responses

Whatever your action returns, Laravel converts into a full HTTP response:

You return The client receives
a string 200 with an HTML body
an array or collection 200 with a JSON body and a JSON content type
a Blade view 200 with rendered HTML
a Response object exactly what you built
a redirect 302 with a Location header
PHP
Route::get('/hello', fn () => 'Hello');                           // text
Route::get('/status', fn () => ['ok' => true]);                   // JSON
Route::get('/page', fn () => view('page', ['title' => 'Hi']));    // HTML

When you need control over status or headers, build the response explicitly:

PHP
return response('Created', 201)
    ->header('X-Request-Id', 'abc123')
    ->withHeaders(['X-A' => '1', 'X-B' => '2']);

return response()->json(['id' => 7, 'title' => 'Hello'], 201);

abort(404);                                // throw an HTTP exception
abort_if(! $user->isActive(), 403);        // conditional abort

The helper response()->json() sets Content-Type: application/json and encodes the array for you. You can also return an Eloquent model or an API resource, and Laravel will encode it as JSON.

Redirects

PHP
return redirect('/dashboard');                         // to a path
return to_route('posts.show', ['post' => 42]);         // to a named route
return back();                                         // to the previous page
return redirect()->away('https://example.com');        // to an external URL

return redirect()->route('posts.index')
    ->with('status', 'Post saved!');                   // flash a message to the next request

with() flashes data into the session for exactly one more request, which is how "Post saved!" banners work; sessions and flash data explains the lifecycle. Always redirect after a successful POST, so that pressing refresh does not submit the form again. This is the post/redirect/get pattern.

Cookies and downloads

PHP
return response('ok')->cookie('theme', 'dark', 60);    // name, value, minutes

return response()->download(storage_path('app/report.pdf'), 'report-2026.pdf');
return response()->file(public_path('terms.pdf'));     // shown inline in the browser
return response()->streamDownload(function () {
    echo "id,name\n1,Ada\n";
}, 'people.csv');

Cookies set by Laravel are encrypted and signed by default, so users cannot read or tamper with them. Streaming a download avoids loading a whole file into memory.

Macros

Both Request and Response are macroable: you can add your own methods at runtime, usually in a service provider's boot() method (see service providers):

PHP
use Illuminate\Support\Facades\Response;

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

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

Macros are handy for project-wide conventions, such as a standard JSON envelope. Do not overuse them: a normal helper class is easier to find and test. Packages and macros returns to this idea.

flowchart LR
    B["Browser"] -->|"HTTP request"| Q["Request object<br/>input, files, headers"]
    Q --> A["Your action"]
    A -->|"string, array, view,<br/>redirect, Response"| P["Response object<br/>status, headers, body"]
    P -->|"HTTP response"| B

The action reads from the request object and returns something that Laravel turns into a response object.

A Request in plain PHP

The stand-in below captures a request from plain arrays. Its input() merges body over query string, supports dot notation, and has has, filled, boolean, only and is. A second request is built from a JSON string. Real Laravel reads these from PHP's superglobals and Symfony's Request class, so details such as file handling are richer.

PHP A Request object with input helpers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Study the has and filled output for draft: the key exists but is an empty string, so one is true and the other false. That distinction trips up many forms.

A Response in plain PHP

Now the other half: a response with a fluent API, JSON and redirect helpers, a cookie and a send() that prints the raw HTTP text. The second part shows the conversion rule from the table above: arrays become JSON, strings become HTML, and responses pass through.

PHP A Response object and return-value conversion

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The real framework adds many more conversions (views, models, Responsable objects, streamed responses) and an encrypted cookie layer, but the shape is the same: normalize whatever came back into one response type, then send it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the difference between $request->has('note') and $request->filled('note')?

    A form field sent as an empty string is present, so has() is true, but it is not filled.
  2. 2. What does a Laravel action that returns an array produce?

    Arrays (and collections or models) are converted to JSON with the right content type.
  3. 3. Why should you not pass $request->all() straight into Model::create()?

    Request data comes from the client. Use validated data or only() with fields you expect, and protect models with fillable.
  4. 4. Which return value sends the user to a named route after a successful form POST?

    to_route() builds a redirect from a route name. Redirecting after POST avoids duplicate submissions on refresh.

Summary

  • The Request object unifies query string, body, JSON, files, headers and cookies; type-hint it instead of using superglobals.
  • Treat all input as untrusted: validate before use, and know the difference between has() and filled().
  • Return strings, arrays, views, redirects or explicit response() objects; Laravel converts them into HTTP responses.
  • redirect(), to_route() and back() with with() implement post/redirect/get and flash messages.
  • Cookies, downloads and streaming have helpers; macros extend Request and Response when you need project-wide behavior.

Next: Middleware