Laravel Response - HTTP Views and Responses | W3Schools

Basic Response
Each and every request is linked with a response. The MVC framework offers you various ways through which you can return a response to a request. You can send the response through two ways: 1. through route 2. through controller. Take a look at the below given sample code to understand how to a send response with the help of a single string. For the convenience of the users, the input string is gets converted to the suitable HTTP response, automatically.

Step 1: Include the following lines of code to the routes.php. You can find this file at app/Http.

Route::get(‘/basic_response’, function ()
return ‘Hello World’;

Step 2: Copy the URL: http://localhost:8000/basic_response to the web server to test the basic response. The output will appear like the following.

Also Read: Laravel Request

Attaching Headers to the Response
To attach a header with a response, you can use header() method. You can attach multiple numbers of headers as displayed below.

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

To understand this, take a look at the following example.

Step 1: Copy the following code to the routes.php. This file can be found on the following route: app/Http.

return response(“Hello”, 200)->header(‘Content-Type’, ‘text/html’);


Step 2: Paste the given URL: http://localhost:8000/header to the web server and you will get the below given output.

Attaching Cookies With Response
You can also attach cookies to the response by the use of withcookie() method. You can use this helper method to attach the generated cookie with the response instance. For all the Laravel users, these cookies are kept encrypted and signed so that no one can modify its contents.

Go through the following example to understand how to attach a cookie with a response instance.

Step 1: Include the following code to the app/Http/routes.php.

return response(“Hello”, 200)->header(‘Content-Type’, ‘text/html’)
->withcookie(‘name’,’Virat Gandhi’);


Step 2: Now, to test the basic response, copy the URL: http://localhost:8000/cookie to the PHP’s web server. You will be displayed with the following page.

JSON Response
Json method is used to send a JSON response. By default, the method will set the Content-Type header to application/json. This method is capable of converting an array into a suitable json response on its own.

For your understanding, here is the example.

Step 1: Follow the path: app/Http/. Here, you will get the routes.php file. In this file, you need to paste the following code.

return response()->json([‘name’ => ‘Virat Gandhi’, ‘state’ => ‘Gujarat’]);

Step 2: Visit the URL: http://localhost:8000/json and you will get to see the following output.