Laravel Responses
A zombie developer does not respond well to their clients, whereas a Laravel developer sends clear and concise responses.
When we refer to Responses we are primarily referring to the output that we send to the client. When our Laravel app receives a request, it can then send a response.
Responses
In the previous section, we talked about requests and how our Laravel app can accept them. In this section we are going to cover responses.
When our app get's a request, it can also return a response.
Here's a simple example of a response:
Route::get('/apocalypse', function () {
echo 'End of the World!';
});
In the example above our laravel app recieves a GET request to the /apocalypse
route and it returns a string as the response. This is the simplest form of a response.
So, when we return a response that contains HTML our Laravel app is essentially returning an HTML document that gets displayed in the users browser.
Attach a Cookie to a Response
In the previous section we talked about how your app can retrieve a cookie, now lets see how we can set a cookie by attaching it to a response. Remember a cookie is stored on the client side (browser), so when our app sends a response it will need to attach a cookie to be set by the browser.
We can easily do this by attaching it to the end of a view response like so:
Route::get('set_cookie', function(){
return response()->view('apocalypse')->withCookie('name', 'value');
});
JSON responses
If we wanted to output a JSON response for a particular route we could use the following syntax:
Route::get('json_response', function(){
$data = array(
'name' => 'Johnny Bullet Holes',
'strength' => 'strong');
return response()->json( $data );
});
By running the route above, we get a nice JSON output as the response.
Lastly, we can perform a redirect as a response like so:
Route:get('redirect_me', function(){
return redirect('zombie/1');
});
or even simpler, we could create a redirect like so:
Route::redirect('redirect_me', 'zombie/1');
The route above will redirect to the site.com/zombie/1
route as a response.
View response
The most common response your app will send is an HTML response from one of your application views.
When you return a view
in your Laravel app, it is essentially the same thing as returning an HTML response. Here is a quick example from a few sections back:
public function show(){
// Show our zombies
$zombies = Zombie::all();
// Load the view and pass it our data array
return view('zombies', compact('zombies') );
}
It's pretty straightforward, right? Our application gets a request and returns a response. There are a few more responses that you may want learn about by checking out the docs here https://laravel.com/docs/responses.
Next, let's move on to something exciting called migrations.
Migrations are a way of storing our database schemas in files so they can easily be versioned, shared, and backed up.