Laravel Response

In this topic, we will learn about Response in Laravel.

Laravel framework 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';
});

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];
});

Attaching Headers To Responses

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)
            ->header('Content-Type', $type)
            ->header('X-Header-One', 'Header Value')
            ->header('X-Header-Two', 'Header Value');

Or, you may use the withHeaders method to specify an array of headers to be added to the response:

return response($content)
            ->withHeaders([
                'Content-Type' => $type,
                'X-Header-One' => 'Header Value',
                'X-Header-Two' => 'Header Value',
            ]);