How to get previous route name in Laravel 5.8

Viewed 809

I'm trying to get previous route name in Laravel 5.8. This answer (https://stackoverflow.com/a/40690569/16735772) works perfectly when I use Virtual Host but in direct url like (125.125.125.125/project_folder/public) does not because NotFoundHttpException is thrown.

With Virtual Host, $request->create(url()->previous()) creates a request with pathInfo and requestUri using relative url, for example, my_profile/2 but without Virtual Host, those attributes have different value, like project_folder/public/my_profile/2.

I don't need to redirect back, just know previous route name to check. For example:

if ($previous_route == 'show_name') {
   //do something
}

Any help will be appreciated.

1 Answers

Try this code to get the previous route name:

Route::getRoutes()->match(
    Request::create(URL::previous())
)->getName();

You can make a helper or blade directive to make it easier to access.

Related