How to redirect a user to the previous page in Laravel
Overview
Most times, when a user session expires, we might want to authenticate to know if it is the same person and then redirect them back to the page they were initially on. In this shot, I will teach you how to send a user back to their initial page with the back() method.
What is the back() method?
The back() method generates a redirect HTTP respond and uses it to send a user back to their previous location.
Syntax
return back();
Parameters
The back() method can be used without a parameter and receives three(3) parameters for advanced usage.
- Status code
- Headers
- Fall back URL
In this shot, we will only use the default back() method.
Example
if(!auth()){
return back();
}
Explanation
The code above is a simple example of how to use the back() method. The code redirects unauthenticated users back to their previous page.