Laravel Application Helper: response

November 20, 2016 —John Koster

response($content = '', $status = 200, array $headers = [])

The response helper function is a useful function that can be used to accomplish two different tasks. If no arguments are supplied to the response function, an implementation of Illuminate\Contracts\Routing\ResponseFactory will be returned (by default this is an instance of Illuminate\Routing\ResponseFactory). The following example demonstrates some of the different methods that are available when the response function is used in this way:

3return response()->view('welcome');
4return response()->json(['Laravel' => 'Artisan']);
5return response()->redirectTo('/');

The response function can also be used as a shortcut to the ResponseFactory::make method. If any arguments are supplied to the response function, the function will internally make a call to the ResponseFactory::make method passing all the arguments and returning the result (a new instance of Illuminate\Http\Response). The following examples are equivalent in their end results:

3return response()->make('I am the response content!');
4return response('I am the response content!');

If the above examples had been returned from a controller or route the user would see the text I am the response content! in their browser.

#Changing the HTTP Status Code

To change the status code of the response simply supply an argument for the $status parameter:

3// Create a response with the `404` status code.
4return response('That page was not found.', 404);

#Supplying Additional Headers

In order to supply extra headers we must also provide an argument for $status and then supply an argument for $headers:

3// Create a response with a "404: Not Found" status code and extra headers:
4return response('Page not found.', 404, [
5 'Cache-Control' => 'public'

Some absolutely amazing

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.