April 14, 2018 —John Koster
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 signature of the response
function is:
1function response(2 $content = '',3 $status = 200,4 array $headers = []5);
The following example demonstrates some of the different methods that are available when the response
function is used in this way:
1return response()->view('welcome');2return response()->json(['Laravel' => 'Companion']);3return 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:
1return response()->make('I am the response content!');2return 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.
To change the status code of the response simply supply an argument for the $status
parameter:
1// Create a response with the `404` status code.2return response('That page was not found.', 404);
In order to supply extra headers we must also provide an argument for $status
and then supply an argument for $headers
:
1// Create a response with a "404: Not Found" status code and extra headers:2return response('Page not found.', 404, [3 'Cache-Control' => 'public'4]);
∎
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.