When building Laravel applications, you often need to send users back to the previous page—think after a form submission or an action completion. The problem?
- The previous URL might not exist in the request history.
- It could match the current page, creating an infinite loop.
- You might want a custom fallback route when history is unavailable.
Instead of writing conditional checks in multiple controllers, we can create a global helper function once and reuse it anywhere.
Creating the Helper backUrl()
Here’s the helper function code:
// A check to ensure the function doesn't get redefined if it already exists.
if (!function_exists('backUrl')) {
/**
* Generate a "back" URL safely, with a fallback to a named route or homepage.
*
* @param string $fallbackRouteName The name of the route to use as a fallback (optional).
* @return string The previous URL, a fallback route URL, or the homepage URL.
*/
function backUrl(string $fallbackRouteName = ''): string
{
// Get the previous URL from the session history.
$previousUrl = url()->previous();
// If a previous URL exists and isn't the current URL, return it.
if ($previousUrl && $previousUrl !== url()->current()) {
return $previousUrl;
}
// If a fallback route name is provided and exists, use that route.
if (!empty($fallbackRouteName) && Route::has($fallbackRouteName)) {
return route($fallbackRouteName);
}
// As a last resort, return the homepage URL.
return url('/');
}
}
How It Works
- Checks previous URL from session history using Laravel’s
url()->previous()
- Prevents redirect loops by ensuring it’s not the current page.
- Allows a fallback route if specified and exists.
- Defaults to the homepage if no history or fallback exists.
Usage Examples
Redirect back with fallback:
return redirect()->to(backUrl('dashboard'));
Get back URL in a Blade view:
<a href="{{ backUrl() }}">Go Back</a>
Why Not Just Use back()
?
Laravel’s back()
helper simply redirects to the previous page. If the HTTP referrer is missing or the same as the current URL, you might get unexpected behavior—or even an infinite loop. This helper adds safety and flexibility.
With this small helper in place, you can handle “go back” logic in a clean, reusable way across your Laravel application.