A web application responds to a user’s request in many ways depending on many parameters.
Laravel provides several different ways to return response. Response can be sent either from route or from controller. The basic response that can be sent is simple string as shown in the below sample code. This string will be automatically converted to appropriate HTTP response.
Visit the following URL to test the basic response.
http://localhost:8000/myresponse
The response can be attached to headers using the header() method. We can also attach the series of headers as shown in the below sample code.
Example :- app/Http/routes.php
Route::get('/header',function() {
return response("Hello", 200)->header('Content-Type', 'text/html');
});
check the url :- http://localhost:8000/header
The withcookie() helper method is used to attach cookies. The cookie generated with this method can be attached by calling withcookie() method with response instance. By default, all cookies generated by Laravel are encrypted and signed so that they can't be modified or read by the client.
http://localhost:8000/cookie
JSON response can 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 appropriate json response.
Trending Tutorials