Laravel 5: HTTP Layer – Requests

Laravel 5: HTTP Layer – Requests


HTTP request, is exactly what the name suggest.
It is a request sent by client to server for some resource.
It could be anything: text, image, data processing, data stored in database etc.
Of course there is more to it, but in general, above covers it.

Accessing The Request
Dependency injection

To access request just inject type hinted dependency like so:

Dependency Injection & Route Parameters

Your route may accept parameter coming with URI, e.g. like this:

{id?} is parameter I am talking about.
Question mark means, that such parameter is optional.
Optional parameter must have default value set.

If you are using dependency injection, just insert parameter after dependency.
If you have more params, just list them one after another in order they are coming in route.

Here’s how it should look like:

Accessing The Request Via Route Closures

You can access Request via dependency injection into closure directly in route file, like so:

Note, that optional parameter id (denoted by ‘?’) has default value ‘null’.
Default value can be anything, but it has to be set for optional param, or exception (error) will be thrown.

Request Path & Method

Full set of tools is here in API.
Link above links to Laravel 5.3 API.

First, something not listed in Laravel API, but it is available via Symfony Http-foundation:

method() / isMethod()

The method method will return the HTTP verb for the request. You may use the isMethod method to verify that the HTTP verb matches a given string:

Rest of these methods provided by Laravel and described in API just need to be chained to $request object and voila.

Retrieving input

See full list of Http/Request API here.