Request & Response — Laravel

Write Request $request as a controller method parameter, and Laravel fills it with the incoming request. input('name') reads one field (one filled-in value)…

Where does a JSON body (the content of a request, written as JSON) go in plain PHP? Not into $_POST. You have to read it yourself with file_get_contents('php://input'), then json_decode. Form fields are in $_POST, the query string in $_GET, and the headers (extra notes sent along with the request) in $_SERVER. Answering takes several steps too: http_response_code(201), header('Content-Type: application/json'), and only then echo json_encode(...).

Laravel gathers everything the client (the sender of the request, for example a browser) sent into one Request object: the HTTP method, the address, the query string, the body and the headers. The value you return from a controller method becomes the response, which holds a status, headers and a body.

Picture the library's counter. The clerk takes a loan form and reads its fields one by one. Then the clerk hands back a slip stamped "accepted" or "refused". The clerk is the controller method, the form is the request, the slip is the response, and the stamp on the slip is the status.

Reading the request

The Library admin adds a book through POST /books, with this request:

POST /books?draft=1 HTTP/1.1
Host: 127.0.0.1:8000
Content-Type: application/json

{"title": "The Dancer", "author": "Ahmad Tohari"}

The first line holds the method and the address, including the query string ?draft=1. Then come the headers, one blank line, and the JSON body. This request is answered by BookController@store, the method store in BookController:

use Illuminate\Http\Request;

public function store(Request $request)
{
    $book = [
        'id' => 4,
        'title' => $request->input('title'),
        'author' => $request->input('author'),
        'stock' => $request->input('stock', 1),
    ];

    return response()->json($book, 201);
}

Here's the value of each call for the request above:

Call Result
$request->method() 'POST'
$request->path() 'books'
$request->input('title') 'The Dancer'
$request->input('stock', 1) 1, because it wasn't sent
$request->query('draft') '1', only from the query string
$request->only(['title', 'author']) ['title' => 'The Dancer', 'author' => 'Ahmad Tohari']
$request->all() every field: title, author and draft
$request->title 'The Dancer', the short way

So the method store answers 201 Created with {"id":4,"title":"The Dancer","author":"Ahmad Tohari","stock":1}. Field names are case-sensitive, so input('Title') gives null.

Laravel only reads a JSON body when the request carries the header Content-Type: application/json, which says that the body is JSON. Without that header, input('title') is null too. This header is covered in more detail in the API track, in the Request & Response lesson.

The shapes of a response

Whatever a method returns, Laravel turns it into a response:

What you return Status What the client gets
'Hello' 200 OK text, Content-Type: text/html; charset=UTF-8
['title' => 'The Rainbow Troops'] 200 OK JSON {"title":"The Rainbow Troops"}
response()->json($book, 201) 201 Created JSON
response()->noContent() 204 No Content no body
redirect()->route('books.show', ['book' => 4]) 302 Found the header Location: http://127.0.0.1:8000/books/4
view('books.index', [...]) 200 OK HTML from Blade, in the next lesson
abort(404) 404 Not Found the Not Found page

An array becomes JSON, with the header Content-Type: application/json and status 200. The result is not an error, and not the text Array (what echo prints for an array). response()->json is still useful when you need another status, or when you want the code to show clearly that the answer is JSON.

A redirect is an answer that tells the browser to go to another address. A redirect carries no data: the browser goes right to the address in the Location header. Extra headers are set with ->header(...), for example response()->json($book)->header('Cache-Control', 'no-cache').

The statuses you'll meet most

What each group of statuses means is covered in more detail in the API track. In Laravel, these come up most: 200 and 201 success, 204 success with no body, 302 a redirect, 404 not found, 405 the wrong method, 419 refused by the CSRF guard, 422 input that fails validation (checking what was typed in, in the Validation lesson), and 500 an error in your code.

419 | Page Expired confuses many people. Routes in routes/web.php refuse POST, PUT, PATCH and DELETE from outside your app. A request from your own page is accepted, because of one of two things: the browser sends the header Sec-Fetch-Site: same-origin (a sign that the request comes from the same site), or the form carries a token (a random code) that @csrf adds (a Blade command, in the next lesson). A request from curl or Postman (an app for trying out requests) carries neither, so it's refused. API routes in routes/api.php don't use this guard.

The exercise: POST /register

In the exercise, the code has the same shape as store above, but written as a function inside Route::post: the route POST /register reads name and email from the request, then answers 201 with {"name": ..., "email": ..., "status": "registered"}.

When you press Run, the route is called with an empty body. $request->input(...) gives null for a field that wasn't sent, so the output is POST /register → 201 then {"name":null,"email":null,"status":"registered"}. The checker also sends {"name": "Sinta", "email": "[email protected]"} and expects that name and email to come back, exactly.

⚠️ Hard-coded values, forgotten statuses

TL;DR: Write Request $request as a controller method parameter, and Laravel fills it with the incoming request. input('name') reads one field (one filled-in value) from the body (the content of the request) or the query string (input('name', default) for a default value). query() reads only the query string, only([...]) a few fields, and all() everything. A JSON body is only read when the request carries the header Content-Type: application/json. Whatever you return becomes the response: a string becomes HTML, an array becomes JSON, response()->json($data, 201) for JSON with another status, noContent() for 204 (no body), and redirect()->route(...) for 302 (go to another address). A POST from outside the app to routes/web.php gets 419 from the CSRF guard (protection against forged requests).

⚡ Read what the client sent

Write:

public function store(Request $request)
{
    $book = [
        'title' => $request->input('title'),
        'stock' => $request->input('stock', 1),
    ];

    return response()->json($book, 201);
}

Meaning: Write Request $request as a method parameter, and Laravel fills it with the request that comes in from the client (for example a browser). input('title') reads one field (one filled-in value) from the body (the content of the request) or from the query string, and input('stock', 1) uses 1 when stock wasn't sent. The 201 at the end is the status 201 Created: new data was created.

⚡ What you return becomes the response

Guess first: return ['title' => 'The Rainbow Troops']; reaches the client as what?

JSON {"title":"The Rainbow Troops"} with status 200. Not an error, not the text Array.

Meaning: Laravel turns the value a method returns into a response: a string becomes HTML, an array becomes JSON. Use response()->json($data, 201) for another status, noContent() for 204 (success with no body), and redirect()->route(...) for 302 (the browser is told to go to another address).

⚡ Take it from the request, don't type it

Meaning: Take values from $request, don't type them yourself in the code: a typed value is only right for one sender. Field names are case-sensitive, so input('Title') gives null. A field that wasn't sent is null too. A POST from curl (a program that sends requests from the terminal) to routes/web.php gets 419: that's the CSRF guard, which refuses requests from outside your app, not a bug in your route.

In the exercise, take name and email with $request->input(...). The checker also sends Sinta's name and email, and expects the same values back.

What you will learn