Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Requests and responses

Every visit to a site is a request the application must answer. In Laravel a request is represented by the Request object, and helper functions build the response. With them you never touch $_GET, $_POST or headers directly.

The request object

Laravel passes the request object into a controller method if you list it among the parameters:

use Illuminate\Http\Request;
 
public function store(Request $request)
{
    $title = $request->input('title');
    $page = $request->query('page', 1);
 
    return "Title: $title";
}

input() reads form data and JSON, query() reads parameters from the address. The second argument is a default value.

Handy reading methods

$name = $request->string('name')->trim();
$age = $request->integer('age');
$subscribed = $request->boolean('subscribe');
$date = $request->date('birthday');
 
$data = $request->only(['title', 'body']);
$rest = $request->except(['_token']);

boolean() understands the values 1, true, on, yes — handy for checkboxes.

Checking for presence

if ($request->has('email')) {
    // the field was sent
}
 
if ($request->filled('email')) {
    // the field was sent and is not empty
}

Information about the request

$request->method();        // GET, POST…
$request->path();          // posts/5
$request->url();           // the address without parameters
$request->ip();            // the visitor's address
$request->header('Accept');
$request->user();          // the logged-in user or null
$request->isMethod('post');

A response: a string, an array, a template

Whatever a controller method returns becomes the response:

return 'Plain text';
 
return ['id' => 1, 'title' => 'Tea'];  // becomes JSON
 
return view('posts.show', ['post' => $post]);

The status code and headers

The response() function gives full control over the response:

return response('Not found', 404);
 
return response()->json(['error' => 'Forbidden'], 403);
 
return response($content)->header('Content-Type', 'text/plain');

The abort() function stops execution and shows an error page: abort(404).

Redirecting

return redirect('/posts');
 
return redirect()->route('posts.show', $post);
 
return back()->withInput();
 
return redirect()->route('posts.index')->with('status', 'Post saved');

back() returns to the previous page, withInput() keeps the entered data for the old() function, and with() passes a one-time message.

Files

return response()->download(storage_path('app/report.pdf'));
 
return response()->file(storage_path('app/photo.jpg'));

download() offers to save the file, file() shows it right in the browser.

Common mistake

A value from a request is always a string, even if a number was typed into the field. The comparison $request->input('page') === 2 is always false. Use the type-casting methods — integer(), boolean() — or validation rules.

Thanks for reading!

Donate to the site — we work hard for you.