Concept of Http Response in Laravel Tutorial

This tutorial explains, HTTP response in laravel web application.

Basic Response

Laravel provides a number of different ways to return a response. Response may be sent both from route or from controller. The primary response that may be despatched is a straightforward string as shown within the below pattern code. This string will likely be automatically converted to an acceptable HTTP response.

Basic Examples:

Add the below code in the routes/web.php file & Visit the URL: http://YOUR_DOMAIN/response.

Route::get('/response', function () {
   return 'Hello World';

Attach Header

The response may be connected to headers using the header() method. We also can connect the series of headers as shown within the below pattern code.

return response($content,$status)
   ->header('Content-Type', $type)
   ->header('X-Header-One', 'Header Value')
   ->header('X-Header-Two', 'Header Value');


Add the below code within the routes/web.php files & Visit the URL: http://YOUR_DOMAIN/header.

Route::get('/header',function() );

Attach Cookies

The withcookie() helper method is used to connect cookies. The cookie generated with this method may be connected by calling withcookie() method with a response instance. By default, all cookies generated by Laravel are encrypted and signed in order that they can not be modified or read by the client.

Add the below code within the routes.web.php & Visit the URL: http://YOUR_DOMAIN/cookie.


   return response("Hello", 200)->header('Content-Type', 'text/html')
      ->withcookie('name','Abhay Anand');

Json Response

JSON response may be sent using the json method. This method will automatically set the Content-Type header to application/json. The json method will automatically convert the array into acceptable json response.

Add the below code within the routes.web.php & Visit the URL: http://YOUR_DOMAIN/json.

Route::get('json',function() {
   return response()->json(['name' => 'Abhay Anand', 'Country' => 'India']);

<— Previous Tutorial


Please enter your comment!
Please enter your name here


Related Articles

Concept of Session in Laravel Tutorial

Sessions are used to store details about the user throughout the requests. Laravel supplies various drivers like file, cookie, apc, array, Memcached, Redis, and database to handle session data. By default, file driver is used as a result of it's light-weight....

Laravel Url Generation Tutorial

Our web application revolves around routes and URLs. After all, they're what direct our users to our pages. At the end of the day, serving pages is what any web application should do. Our users may...

Concept of Laravel Views Tutorial

In MVC framework, the letter "V" stands for Views. It separates the application logic and presentation logic. Views are saved in resources/views listing. Generally, the view contains the HTML which might be served by the application.
WP2Social Auto Publish Powered By :