Laravel 5.1-5.8 中以前的路线名称
Posted
技术标签:
【中文标题】Laravel 5.1-5.8 中以前的路线名称【英文标题】:Previous route name in Laravel 5.1-5.8 【发布时间】:2017-04-03 01:53:58 【问题描述】:我尝试在 Laravel 5.1 中查找先前路线的名称。 与:
!! URL::previous() !!
我得到了路由 url,但我尝试获取当前页面的路由名称:
!! Route::current()->getName() !!
我的客户不会为 感谢页面 提供不同的文本,这取决于从页面(注册页面或联系页面)用户转到 感谢页面。我尝试:
!! Route::previous()->getName() !!
但这没有用。我试图得到类似的东西:
@if(previous-route == 'contact')
some text
@else
other text
@endif
【问题讨论】:
【参考方案1】:您只需这样做即可实现它。希望对你有帮助
在控制器中:
$url = url()->previous();
$route = app('router')->getRoutes($url)->match(app('request')->create($url))->getName();
if($route == 'RouteName')
//Do required things
在刀片文件中
@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
【讨论】:
【参考方案2】:这对我有用。我找到了这个答案和这个问题,并将其修改为适用于我的情况:https://***.com/a/36476224/2807381
@if(app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName() == 'public.contact')
Some text
@endif
5.8 版更新Robert
app('router')->getRoutes()->match(app('request')->create(url()->previous()))->getName()
【讨论】:
如果还实现了 Route::fallback,Laravel 将始终将此作为匹配的路由返回。有人有解决方法吗?app('router')->getRoutes()->match(app('request')->create(url()->previous()))->getName()
这是 5.8 中的工作示例【参考方案3】:
我已经创建了一个这样的辅助函数。
/**
* 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;
【讨论】:
【参考方案4】:您无法获取上一页的路线名称,因此您的选择是:
检查以前的 URL 而不是路由名称。
使用sessions。首先,保存路由名称:
session()->flash('previous-route', Route::current()->getName());
然后检查会话是否有previous-route
:
@if (session()->has(`previous-route`) && session(`previous-route`) == 'contacts')
Display something
@endif
-
使用
GET
参数传递路由名称。
如果我是你,我会使用会话或检查以前的 URL。
【讨论】:
以上是关于Laravel 5.1-5.8 中以前的路线名称的主要内容,如果未能解决你的问题,请参考以下文章