Laravel 5: HTTP Layer – Responses

Laravel 5: HTTP Layer – Responses


This is what your system sends to browser after dealing with request.

When you get request from client, process it, in 99% of cases, you are expected to deliver some response.

View Responses

This is most common response type.

User clicks on a link, or uploads form, you process it and send user an response in a form of a new page.

Usually, it looks like this:

If you want to pass some data back to blade template, you can send it in a form of an array as a second argument, like so:

If you want to pass some additional stuff, like headers etc., you can do this like here (note response()):

200 is a HTTP status code.

$type is a MIME type – here is a list.

 

JSON Responses

When you build API, you want to send response as JSON, as you do not need all that human wrapper shtick.

To accomplish that, you chain json() method onto response, like so:

If, for whatever reason, you need jsonp, just chain withCallback():

And you are set.

 

Redirect
Basic
Simplest way is to use global redirect() function:

Redirect to previous location, e.g. when submitted form had some errors:

withInput() part is really great, as it returns data, you need to repopulate form.

Redirecting To Named Routes

You can define a keyword for a route and then use it application wide.
See here how it is done – scroll down to “Naming/Defining Routes So They Can Be Used Anywhere“.

Once you have a named route, you can easily redirect to it, by using its keyword name, like so:

If our route expects parameters, we can pass them in second argument, like so:

Populating Parameters Via Eloquent Models

Laravel is good at doing some stuff for us automatically.

From $user model, Laravel can automatically pluck id and push it into expecting it route.

 

Other Uses

You can also use it to attach headers, cookies etc. to responses.

Read about this in Laravel docs.