Laravel Application Helper Function: back

November 20, 2016 —John Koster

back($status = 302, $headers = [])

The back helper function is used to create a redirect response to the user's previous location. It defines two parameters which can be used to control the status code and headers of the response. An integer argument can be supplied for the $status parameter to change the HTTP status code for the request. By default, the code is 302 ("Found"), but could easily be changed to 301 ("Moved Permanently"). Specific headers can also be set by providing an argument for the $headers parameter. There is an example of this below. The back function returns an instance of Illuminate\Http\RedirectResponse.

The following examples show different ways to return a RedirectResponse from a controller action. The examples assume that some controller class exists with a method named postCreateSomeValue. The actual details of the controller class and method are not important for these examples.

#Returning a Redirect Response Using the Redirect Facade

The Redirect facade resolves to an instance of Illuminate\Routing\Redirector, which is where the back method is defined:

1<?php
2 
3use Illuminate\Support\Facades\Redirect;
4 
5function postCreateSomeValue() {
6 // ... code here ...
7 return Redirect::back();
8}

#Returning a Redirect Response Using the response Helper Function

Like the Redirect facade, the redirect helper function will resolve an instance of Illuminate\Routing\Redirector from the service container and then all the back method that is defined there:

1<?php
2 
3function postCreateSomeValue() {
4 return redirect()->back();
5}

#Returning a Redirect Response Using the back Helper Function:

1<?php
2 
3function postCreateSomeValue() {
4 // ... code here ...
5 return back();
6}

#Changing the HTTP Status Code

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

1<?php
2 
3// Redirect back with a "301: Moved Permanently" status code.
4return back(301);
5 
6// Redirect back with a "307: Temporary Redirect" status code.
7return back(307);

#Supplying Additional Headers

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

1<?php
2 
3// Redirect back with a "302: Found" status code and extra headers:
4 
5return back(302, ['Laravel' => 'Artisan']);

The following image shows the results of a request that contains the request headers. You can see that the Laravel header is present: Laravel Application Helper Function: back | Verifying the extra header is present using Google Chrome Developer Tools.

Some absolutely amazing
people

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.