Laravel 5: Redirecting Users to the Previous Page With back

April 14, 2018 —John Koster

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".

#Signature

The signature of the back method is:

1function back(
2 $status = 302,
3 $headers = [],
4 $fallback = false
5);

#Example Use

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:

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

#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 
2function postCreateSomeValue() {
3 return redirect()->back();
4}

#Returning a redirect response using the back helper function:

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

#Changing the HTTP Status Code

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

1 
2// Redirect back with a "301: Moved Permanently" status code.
3return back(301);
4 
5// Redirect back with a "307: Temporary Redirect" status code.
6return 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// Redirect back with a "302: Found" status code and extra headers:
2 
3return 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:

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.