In this tutorial you will learn about the Laravel Response and its application with practical example.
In Laravel, a response is what sent back to the user’s browser when a request made. All routes and controllers are meant to return some response as per the request. In Laravel, a response can be return in various ways.
Basic Response
In Laravel, simplest response is just to return a string from a controller or route.
Example:-
1 2 3 |
Route::get('/hello', function () { return 'Hello World'; }); |
Attaching Headers
Headers can also be attached to a response using “header” or “withHeaders” method.
Syntax:-
1 2 3 4 5 6 7 8 9 10 11 12 13 |
return response($content,$status) ->header('Content-Type', $type) ->header('X-Header-One', 'Header Value') ->header('X-Header-Two', 'Header Value'); Or return response($content,$status) ->withHeaders([ 'Content-Type' => $type, 'X-Header-One' => 'Header Value', 'X-Header-Two' => 'Header Value', ]); |
Example:-
1 2 3 |
Route::get('/withheader',function(){ return response("Hello World", 200)->header('Content-Type', 'text/html'); }); |
Attaching Cookies
Cookies can also be attached to response using “cookie” helper method.
Syntax:-
1 2 3 |
return response($content,$status) ->header('Content-Type', $type) ->cookie('name', 'value'); |
Example:-
1 2 3 4 |
Route::get('/withcookie',function(){ return response("Hello", 200)->header('Content-Type', 'text/html') ->cookie('name','John'); }); |
JSON Response
If you want to return a JSON response it can be done using “json” method.
1 2 3 |
Route::get('withjson',function(){ return response()->json(['name' => 'John', 'status' => 'active']); }); |
View Response
If you want to return a view in response with custom status and headers, to do this “view ” helper method can be used in following way –
1 2 3 |
return response() ->view('helloworld', $data) ->header('Content-Type', $type); |
Force File Download
If you want to generate a force download response it can be done using “download” method.
1 |
return response()->download($pathToFile, $fileName, $headers); |