gpt4 book ai didi

Laravel Route::管理员组

转载 作者:行者123 更新时间:2023-12-02 16:48:42 25 4
gpt4 key购买 nike

如果用户是管理员,我想验证一些路由。

Route::get( '/user/{data}', 'UserController@getData' );
Route::post( '/user/{data}', 'UserController@postData' );

现在,我在 Controller 中完成了它:

public function getData( $data = 'one' )
{
if ( Auth::user()->permission == 'admin' ) {
//...
} else {
//...
}
}

public function postData( Request $request, $data = 'one' )
{
if ( Auth::user()->permission == 'admin' ) {
//...
} else {
//...
}
}

我想用 Route::group 来实现,但是如何在 paths.php 中做到这一点?

最佳答案

您可以create middleware这将检查用户是否是管理员:

class IsAdmin
{
public function handle($request, Closure $next)
{
if (Auth::user()->permission == 'admin') {
return $next($request);
}

return redirect()->route('some.route'); // If user is not an admin.
}
}

Kernel.php中注册:

protected $routeMiddleware = [
....
'is.admin' => \App\Http\Middleware\IsAdmin::class,
];

然后将其应用到路由组:

Route::group(['middleware' => 'is.admin'], function () {
Route::get('/user/{data}', 'UserController@getData');
Route::post('/user/{data}', 'UserController@postData');
});

关于Laravel Route::管理员组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39555865/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com