Laravel 5.4:如何为route()函数设置第一个和默认参数
我正在向我的webiste上的所有路由传递前缀参数:Laravel 5.4:如何为route()函数设置第一个和默认参数,laravel,laravel-5.4,Laravel,Laravel 5.4,我正在向我的webiste上的所有路由传递前缀参数: Route::prefix("{param}")->group(function () { # code... }); 有时我需要在视图中调用route()函数。问题就在这里,因为我需要将$param作为第一个参数传递,如下所示: 参考资料\views\welcome.blade.php <a href="{{ route('about-us', $param) }}">About Us</a> 有没
Route::prefix("{param}")->group(function () {
# code...
});
有时我需要在视图中调用route()
函数。问题就在这里,因为我需要将$param
作为第一个参数传递,如下所示:
参考资料\views\welcome.blade.php
<a href="{{ route('about-us', $param) }}">About Us</a>
有没有办法创建中间件并将“全局”配置设置为
route()
函数?在控制器中,您可以像这样保护路由:
public function __construct()
{
$this->middleware('auth');
}
及
Route::get('/about', 'yourcontroller@yourmethod')->name('name');
或者在web.php中,您可以声明一个没有前缀的组,如下所示
Route::namespace('name')->group(function () {
Route::get('/about', 'yourcontroller@yourmethod')->name('name');
});
是的,像这样:
Route::get('about-us', 'AboutController@getAboutUs')->name('about-us');
现在,如果您调用
route('about-us')
它将生成指向…/about-us的url。通过使用@William Correa方法,我创建了一个helper函数,将前缀参数设置为默认的Laravel函数helperroute()
app\Helpers\functions.php
function routex($route, $params = [])
{
if (!is_array($params)) {
$params = [$params];
}
// Set the first parameter to App::getLocale()
array_unshift($params, App::getLocale());
return route($route, $params);
}
现在,当我尝试按名称获取到
route()
的链接时,只需使用routex('about-us')
,而routex()
函数将放置一个前缀参数,如App::getLocale()
或任何您想要的参数。当然!但是我仍然需要为所有路由传递前缀参数{param}
。然后我需要在我的route()
函数中使用$param
。问题是:如何为所有视图的每个调用的route()
函数设置$param
,即使我没有像
那样设置它?从所有路由获取{param}
并将其传递给控制器,然后将$param
传递给视图是不好的。是的!我知道我可以通过使用中间件来保护我的路线。所以…这不是问题。我需要避免从所有路由向所有控制器传递{param}
,因为{param}
是URL的前缀。我只需要在我创建的自定义中间件上使用前缀,而不需要控制器/视图。然后创建两个组:一个带前缀的组和一个不带前缀的组。但如果我不传递前缀参数,我的应用程序如何知道该参数?
function routex($route, $params = [])
{
if (!is_array($params)) {
$params = [$params];
}
// Set the first parameter to App::getLocale()
array_unshift($params, App::getLocale());
return route($route, $params);
}