Response
Headers, HTTP Codes and Cookies
- We can return with response code, header information and cookies
Route::get('posts',function() use($posts){
return response($posts, 201) //HTTPCode
->header('Content-Type','Application/json') //header
->cookie('MY_COOKIE', 'Weili', 3600); //cookie that expires in 3600 minutes(1 hour)
});
Response Redirect
- We can redirect to another page
Route::get('redirectme',function(){
return redirect('/contact'); //go to contact page
});
Route::get('goback',function(){
return back(); //go to previous page
});
Response a json
- We can easily create a json response (for backend APIs)
Route::get('getjson',function() use($posts){
return response()->json($posts);
});
Response a file
- We can return with a file
Route::get('getfile',function(){
return response()->download(public_path('/image.jpg'),'face.jpg');
});
Response a request
- include the Request class at top of file routes/web.php
use Illuminate\Http\Request;
Route::get('/getresult',function(){
dd(request()->all()); //get all user inputs in the form of an array, dd(dump and die) echos out the result
dd(request()->input('page')); //get user input from form/url/json with that name
dd(request()->request('page',1)); //get user input from url query parameter, default is set to 1
});
- when we navigate to address: localhost/getresult?limit=10&page=5, we get the following
Middleware
- Before middleware: Run before request reaches the controller, eg. verify that user is authenticated
- After middleware: Run after request leaves the controller, eg. add headers to response
- inside the app/Http folder, open filename Kernel.php