Laravel Response

 15 - Oct - 2021
 XpertPhp
 24

Basic Response

The basic response can be to return a string response from the controller or route. when any type of request comes on a particular route or controller, at that time we can give an appropriate HTTP response.
Route::get('/test', function () {
   return 'Hello World';
});

Attaching Headers

The response can be added to the headers through the header method (). so you can see the below syntax and example. Syntax
return response($content,$status)
   ->header('Content-Type', $type)
   ->header('X-Header-One', 'Header Value')
   ->header('X-Header-Two', 'Header Value');
Example
Route::get('/test_header',function() {
   return response("test", 200)->header('Content-Type', 'text/html');
});

Attaching Cookies

The response can be added to the headers through the cookie helper method. so you can see below example. Syntax
return response($content,$status)
   ->header('Content-Type', $type)
   ->withcookie('name','john doe');
Example
Route::get('/test_cookie',function() {
   return response("test", 200)->header('Content-Type', 'text/html')
      ->withcookie('name','john doe');
});

JSON Response

This response can be sent using the JSON method. this method always returns the JSON based response. so you can see the below example.
Route::get('test_json',function() {
   return response()->json(['id'=>1,'name' => 'john doe']);
});