有没有办法在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');
});
Run Code Online (Sandbox Code Playgroud)
导航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>
Run Code Online (Sandbox Code Playgroud)
现在我想要的是调用一个函数或一些能给我当前路径的组名的东西.
例子:
getCurrentRouteGroup()
应该返回quote
getCurrentRouteGroup()
应该返回account
Ale*_*nin 22
这应该工作:
Route::group(['prefix'=>'accounts','as'=>'account.'], function(){
Route::get('/', ['as' => 'index', 'uses' => 'AccountController@index']);
Route::get('connect', ['as' => 'connect', 'uses' = > 'AccountController@connect']);
});
Run Code Online (Sandbox Code Playgroud)
更新
{{ $routeName = \Request::route()->getName() }}
@if(strpos($routeName, 'account.') === 0)
// do something
@endif
Run Code Online (Sandbox Code Playgroud)
Rohit Khatri的替代方案
function getCurrentRouteGroup() {
$routeName = Illuminate\Support\Facades\Route::current()->getName();
return explode('.',$routeName)[0];
}
Run Code Online (Sandbox Code Playgroud)
iga*_*ter 16
您可以使用Route::name()->group(...)
为一组路由的所有名称添加前缀
Route::name('foo.')->prefix('xyz')->group(function() {
Route::get('path', 'SomeController@method')->name('bar');
});
Run Code Online (Sandbox Code Playgroud)
这里route('foo.bar')
解析为url/xyz/path
请参阅相关Laravel 文档
不要忘记在前缀名称中添加点:-)
// 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');
});
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
35695 次 |
最近记录: |