Debug School

rakesh kumar
rakesh kumar

Posted on

Laravel - Response

  1. Strings & Arrays
  2. Attaching Cookies To Responses
  3. Redirects
  4. Redirecting With Input
  5. JSON Responses

A web application responds to a user’s request in many ways depending on many parameters. This chapter explains you in detail about responses in Laravel web applications.

Basic Response
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.

Example
Step 1 − Add the following code to app/Http/routes.php file.


app/Http/routes.php

Route::get('/basic_response', function () {
   return 'Hello World';
});
Enter fullscreen mode Exit fullscreen mode

Step 2 − Visit the following URL to test the basic response.

http://localhost:8000/basic_response
Step 3 − The output will appear as shown in the following image.
Image description

Basic Response
Attaching Headers

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.

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

Example
Observe the following example to understand more about Response −

Step 1 − Add the following code to app/Http/routes.php file.

app/Http/routes.php

Route::get('/header',function() {
   return response("Hello", 200)->header('Content-Type', 'text/html');
});
Enter fullscreen mode Exit fullscreen mode

Step 2 − Visit the following URL to test the basic response.

http://localhost:8000/header
Step 3 − The output will appear as shown in the following image.
Image description

Hello
Attaching Cookies
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.

Example
Observe the following example to understand more about attaching cookies −

Step 1 − Add the following code to app/Http/routes.php file.

app/Http/routes.php

Route::get('/cookie',function() {
   return response("Hello", 200)->header('Content-Type', 'text/html')
      ->withcookie('name','Virat Gandhi');
});
Enter fullscreen mode Exit fullscreen mode

Step 2 − Visit the following URL to test the basic response.

http://localhost:8000/cookie
Step 3 − The output will appear as shown in the following image.
Image description

Hello
JSON Response
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.

Example
Observe the following example to understand more about JSON Response −

Step 1 − Add the following line in app/Http/routes.php file.

app/Http/routes.php

Route::get('json',function() {
   return response()->json(['name' => 'Virat Gandhi', 'state' => 'Gujarat']);
});
Enter fullscreen mode Exit fullscreen mode

Step 2 − Visit the following URL to test the json response.

http://localhost:8000/json
Enter fullscreen mode Exit fullscreen mode

Step 3 − The output will appear as shown in the following image.

Json Response
Image description

Strings & Arrays
All routes and controllers should return a response to be sent back to the user's browser. Laravel provides several different ways to return responses. The most basic response is returning a string from a route or controller. The framework will automatically convert the string into a full HTTP response:

Route::get('/', function () {
    return 'Hello World';
});
Enter fullscreen mode Exit fullscreen mode

In addition to returning strings from your routes and controllers, you may also return arrays. The framework will automatically convert the array into a JSON response:

Route::get('/', function () {
    return [1, 2, 3];
});
Enter fullscreen mode Exit fullscreen mode

Attaching Cookies To Responses
You may attach a cookie to an outgoing Illuminate\Http\Response instance using the cookie method. You should pass the name, value, and the number of minutes the cookie should be considered valid to this method:

return response('Hello World')->cookie(
    'name', 'value', $minutes
);
Enter fullscreen mode Exit fullscreen mode

The cookie method also accepts a few more arguments which are used less frequently. Generally, these arguments have the same purpose and meaning as the arguments that would be given to PHP's native setcookie method:

return response('Hello World')->cookie(
    'name', 'value', $minutes, $path, $domain, $secure, $httpOnly
);
Enter fullscreen mode Exit fullscreen mode

If you would like to ensure that a cookie is sent with the outgoing response but you do not yet have an instance of that response, you can use the Cookie facade to "queue" cookies for attachment to the response when it is sent. The queue method accepts the arguments needed to create a cookie instance. These cookies will be attached to the outgoing response before it is sent to the browser:

use Illuminate\Support\Facades\Cookie;

Cookie::queue('name', 'value', $minutes);
Enter fullscreen mode Exit fullscreen mode

Generating Cookie Instances
If you would like to generate a Symfony\Component\HttpFoundation\Cookie instance that can be attached to a response instance at a later time, you may use the global cookie helper. This cookie will not be sent back to the client unless it is attached to a response instance:

$cookie = cookie('name', 'value', $minutes);

return response('Hello World')->cookie($cookie);
Enter fullscreen mode Exit fullscreen mode

Expiring Cookies Early
You may remove a cookie by expiring it via the withoutCookie method of an outgoing response:

return response('Hello World')->withoutCookie('name');
Enter fullscreen mode Exit fullscreen mode

If you do not yet have an instance of the outgoing response, you may use the Cookie facade's expire method to expire a cookie:

Cookie::expire('name');
Enter fullscreen mode Exit fullscreen mode

Cookies & Encryption
By default, all cookies generated by Laravel are encrypted and signed so that they can't be modified or read by the client. If you would like to disable encryption for a subset of cookies generated by your application, you may use the $except property of the App\Http\Middleware\EncryptCookies middleware, which is located in the app/Http/Middleware directory:

/**

  • The names of the cookies that should not be encrypted. *
  • @var array */
protected $except = [
    'cookie_name',
];
Enter fullscreen mode Exit fullscreen mode

Redirects
**Redirect responses are instances of the **Illuminate\Http\RedirectResponse class, and contain the proper headers needed to redirect the user to another URL. There are several ways to generate a RedirectResponse instance. The simplest method is to use the global redirect helper:

Route::get('/dashboard', function () {
    return redirect('home/dashboard');
});
Enter fullscreen mode Exit fullscreen mode

Sometimes you may wish to redirect the user to their previous location, such as when a submitted form is invalid. You may do so by using the global back helper function. Since this feature utilizes the session, make sure the route calling the back function is using the web middleware group:

Route::post('/user/profile', function () {
    // Validate the request...

    return back()->withInput();
});
Enter fullscreen mode Exit fullscreen mode

JSON Responses

JSON Responses
The json method will automatically set the Content-Type header to application/json, as well as convert the given array to JSON using the json_encode PHP function:

return response()->json([
    'name' => 'Abigail',
    'state' => 'CA',
]);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)