In Laravel 8 and above, you can use the intended method to redirect the user back to their previous page after login. This method will redirect the user to the URL they were trying to access before being prompted to log in.
Here's an example of how to use it in a Breeze authentication controller:
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AuthController extends Controller
{
public function login(Request $request)
{
$credentials = $request->validate([
'email' => ['required', 'email'],
'password' => ['required'],
]);
if (Auth::attempt($credentials)) {
return redirect()->intended('/');
}
return back()->withErrors([
'email' => 'The provided credentials do not match our records.',
]);
}
}
In this example, the intended method is called with the root URL (/) as the fallback URL. If the user was trying to access a different URL before being prompted to log in, they will be redirected to that URL instead.
Note that the intended method should only be used after a successful login attempt. If the login attempt fails, you should redirect the user back to the login page using the back method.