Previous route name in Laravel 5.1-5.8
Stefan Bogdanescu
Founder & Senior Architect · 2026-06-29
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.php
{!! URL::previous() !!}php
{!! Route::current()->getName() !!}php
@if(previous_route_name == 'contact')
some text
@else
other text
@endifA 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:php
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);
}php
@middleware(App\Http\Middleware\SetPreviousRoute)
Route::resource('contacts', 'ContactsController');php
@if(Session::has('previous_route'))
// your code to show thank you page text based on previous route
@endif