有没有办法在laravel中定义路由组的名称?
我想要完成的是要知道当前请求属于哪个组,因此我可以通过当前路由操作激活主菜单和子菜单:
代码:
Route::group(['prefix'=>'accounts','as'=>'account.'], function(){
Route::get('/', 'AccountController@index')->name('index');
Route::get('connect', 'AccountController@connect')->name('connect');
});
Route::group(['prefix'=>'quotes','as'=>'quote.'], function(){
Route::get('/', 'QuoteController@index')->name('index');
Route::get('connect', 'QuoteController@create')->name('create');
});
导航HTML代码
<ul>
<li> // Add class 'active' when any route is open from account route group
<a href="{{route('account.index')}}">Accounts</a>
<ul>
<li> // Add class 'active' when connect sub menu is clicked
<a href="{{route('account.connect')}}">Connect Account</a>
</li>
</ul>
</li>
<li> // Add class 'active' when any route is open from quote route group
<a href="{{route('quote.index')}}">Quotes</a>
<ul>
<li> // Add class 'active' when create sub menu is clicked
<a href="{{route('quote.create')}}">Create Quote</a>
</li>
</ul>
</li>
</ul>
现在我想要的是调用一个能给我当前路线的组名的函数或其他东西。
示例:
getCurrentRouteGroup()
页面,则应返回quote
getCurrentRouteGroup()
应该返回account
答案 0 :(得分:14)
这应该有效:
Route::group(['prefix'=>'accounts','as'=>'account.'], function(){
Route::get('/', ['as' => 'index', 'uses' => 'AccountController@index']);
Route::get('connect', ['as' => 'connect', 'uses' = > 'AccountController@connect']);
});
Look here获取解释并在official documentation(路线组和指定路线下)。
<强>更新强>
{{ $routeName = \Request::route()->getName() }}
@if(strpos($routeName, 'account.') === 0)
// do something
@endif
来自Rohit Khatri的替代
function getCurrentRouteGroup() {
$routeName = Illuminate\Support\Facades\Route::current()->getName();
return explode('.',$routeName)[0];
}
答案 1 :(得分:0)
试试这个
Route::group(['prefix'=>'accounts','as'=>'account.'], function(){
Route::get('connect', [
'as' => 'connect', 'uses' => 'AccountController@connect'
]);
});
答案 2 :(得分:0)
// both the format of defining the prefix are working,tested on laravel 5.6
Route::group(['prefix'=>'accounts','as'=>'account.'], function() {
Route::get('/', 'SomeController@index')->name('test');
Route::get('/new', function(){
return redirect()->route('account.test');
});
});
Route::group(['prefix' => 'admin', 'as' => 'admin.'], function () {
Route::get('/', [
'as' => 'custom',
'uses' => 'SomeController@index'
]);
Route::get('/custom', function(){
return route('admin.custom');
});
});
答案 3 :(得分:0)
它应该工作-
内部刀片-
{{ $yourRouteName = \Request::route()->getName() }}
// Find the first occurrence of account in URL-
@if(strpos($routeName, 'account.') === 0)
console the message or your code
@endif