Previous route name in Laravel 5.1-5.8
Stefan Izdrail
Founder & Senior Architect · 2026-06-29
Title: Finding Previous Route Names in Laravel 5.1-5.8
Body:
In Laravel 5.x versions (5.1 to 5.8), route names play a crucial role when rendering dynamic content based on the current or previous routes. While URL::previous() provides the URL of the preceding page, you might need to access the name of that previous route for more contextual control in your application.
Understanding Route Names and Previous Routes
Route names are unique identifiers assigned to each route defined within your Laravel app. They allow easier navigation between routes by referring to their names rather than the full URL. Using the previous() helper, you can access the previous page's URL. However, as mentioned in your initial query, you also want to know its corresponding route name.Accessing Previous Route Names using Laravel
Unfortunately, there is no direct route method that returns the previous route's name, but we can work around this by combining existing methods and some logical checking. Here is a basic approach: 1. Use the URL::previous() helper to get the URL of the previous page.{!! URL::previous() !!}
2. Obtain the current route name using Route::current()->getName().
{!! Route::current()->getName() !!}
3. Compare these two values to determine if they belong to the same set of routes: your "Register", "Contact" and "Thank You" pages.
4. If you find a match, store another variable to hold the appropriate thank you page text for the user's previous route.
5. Use a conditional statement (such as an @if statement) to check this variable and render the corresponding text.
@if(previous_route_name == 'contact')
some text
@else
other text
@endif
A Better Option: Using Middleware for Consistent Control
The approach mentioned above works but can be cumbersome, especially when handling multiple pages. A more efficient and maintainable solution is to leverage middlewares that will handle this logic automatically. Here's a simple example that can be added as a middleware to your application:public function handle($request, Closure $next) {
$previousRouteName = Route::current()->getName();
// We'll store the previous route name in session.
Session::put('previous_route', $previousRouteName);
return $next($request);
}
Now, you simply need to use this middleware on your application routes:
@middleware(App\Http\Middleware\SetPreviousRoute)
Route::resource('contacts', 'ContactsController');
To access the previous route name in your view, use Session::get():
@if(Session::has('previous_route'))
// your code to show thank you page text based on previous route
@endif
By using middleware, your application logic becomes more streamlined and easier to maintain. Furthermore, this solution provides consistent control over the thank you pages, regardless of the number and complexity of the routes involved in your app.