Laravel 5.1-5.8中的上一个路由名称

26

我试图在Laravel 5.1中查找上一个路由的名称。

{!! URL::previous() !!}

我获得了路由的URL,但我尝试获取与当前页面相同的路由名称:

{!! Route::current()->getName() !!}

我的客户希望根据用户访问“感谢页面”的来源页面(“注册页面”或“联系页面”),提供不同的文本。我尝试了以下方法:

{!! Route::previous()->getName() !!}

但那并没有起作用。我试图得到类似于:

@if(previous-route == 'contact')
  some text
@else
  other text
@endif
5个回答

48

以下是适用于我的方法。我找到了这个答案和这个问题,并修改它以适应我的情况:https://dev59.com/e2Af5IYBdhLWcg3wey3Z#36476224

@if(app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName() == 'public.contact')
    Some text
@endif

5.8版本更新 by Robert

app('router')->getRoutes()->match(app('request')->create(url()->previous()))->getName()

如果同时实现了Route::fallback,Laravel将始终将其作为匹配的路由返回。有人有解决方法吗? - Bert H
3
这是5.8版本中的工作示例:app('router')->getRoutes()->match(app('request')->create(url()->previous()))->getName()。它的功能是获取前一个URL所匹配的路由名称。 - Robert

14

简单地说,您可以这样做来实现它。希望有所帮助。

在控制器中:

$url = url()->previous();
$route = app('router')->getRoutes($url)->match(app('request')->create($url))->getName();

if($route == 'RouteName') {
    //Do required things
 }

在 Blade 文件中

@php
 $url = url()->previous();
 $route = app('router')->getRoutes($url)->match(app('request')->create($url))->getName();
@endphp

@if($route == 'RouteName')
   //Do one task
@else
  // Do another task
@endif

9

您无法获取前一个页面的路由名称,因此您的选项如下:

  1. Check previous URL instead of a route name.

  2. Use sessions. First, save route name:

    session()->flash('previous-route', Route::current()->getName());
    

然后检查会话是否有previous-route

@if (session()->has(`previous-route`) && session(`previous-route`) == 'contacts')
    Display something
@endif
  1. 使用GET参数传递路由名称。

如果我是你,我会使用会话或检查以前的URL。


4
我创建了一个类似这样的辅助函数。
/**
 * Return whether previous route name is equal to a given route name.
 *
 * @param string $routeName
 * @return boolean
 */
function is_previous_route(string $routeName) : bool
{
    $previousRequest = app('request')->create(URL::previous());

    try {
        $previousRouteName = app('router')->getRoutes()->match($previousRequest)->getName();
    } catch (\Symfony\Component\HttpKernel\Exception\NotFoundHttpException $exception) {
        // Exception is thrown if no mathing route found.
        // This will happen for example when comming from outside of this app.
        return false;
    }

    return $previousRouteName === $routeName;
}

0

Route::getRoutes()->match(request()->create(url()->previousPath()))->getName();


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接