Laravel可选路线参数 [英] Laravel Optional Route Parameters

查看:106
本文介绍了Laravel可选路线参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Route::get('dashboard/{path?}', function($path= null)
{
    return $path;
});

是的,是的

如果网址是

仪表板/电影/搞笑/../..

获取 NotFoundHttpException

推荐答案

默认情况下为路由参数不能包含任何斜杠,因为多个路由参数或线段之​​间用斜杠分隔。

Per default a route parameter cannot contain any slashes, because multiple route parameters or segments are separated by slashes.

如果路径级别有限,则可以执行以下操作:

If you have a finite number of path levels you could do this:

Route::get('dashboard/{path1?}/{path2?}/{path3?}', function($path1 = null, $path2 = null, $path3 = null)

但是,这不是很优雅,也不动态,您的示例表明可能存在很多路径级别。您可以使用where约束在route参数中使用斜线,因此该路由基本上可以捕获以 dashboard 开头的所有内容p>

However this isn't very elegant nor dynamic and your example suggests there can be many path levels. You can use a where constraint to allow slashes in the route parameter. So this route will basically catch everything that starts with dashboard

Route::get('dashboard/{path?}', function($path= null){
    return $path;
})->where('path', '(.*)');

这篇关于Laravel可选路线参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆