我如何根据 laravel 中的用户角色管理控制器方法?
How can i manage controller methods as per user role in laravel?
public function __construct()
{
$this->middleware('roles:Author')->only(['index','show','create']);
$this->middleware('roles:User')->only(['index','show']);
}
在我的控制器中,我希望根据用户角色访问方法,例如,如果用户角色是管理员,那么他必须访问控制器的所有方法,如果用户角色是作者,那么他可以访问索引、创建和显示方法,以及如果角色是 User 那么他只能访问 index 和 show 方法。
你可以看看Gates
(docs).
在您的 App\Providers\AuthServiceProvider
中添加:
Gate::define('create-post', function ($user) {
return $user->isAuthor(); //Here you should check the users role
});
然后在你的控制器方法中 create()
:
if (Gate::allows('create-post')) {
// The current user can create posts...
}
其他两种方法:index()
和 show()
对两个角色都可用,因此无需执行任何操作。
public function __construct()
{
$this->middleware('roles:Author')->only(['index','show','create']);
$this->middleware('roles:User')->only(['index','show']);
}
在我的控制器中,我希望根据用户角色访问方法,例如,如果用户角色是管理员,那么他必须访问控制器的所有方法,如果用户角色是作者,那么他可以访问索引、创建和显示方法,以及如果角色是 User 那么他只能访问 index 和 show 方法。
你可以看看Gates
(docs).
在您的 App\Providers\AuthServiceProvider
中添加:
Gate::define('create-post', function ($user) {
return $user->isAuthor(); //Here you should check the users role
});
然后在你的控制器方法中 create()
:
if (Gate::allows('create-post')) {
// The current user can create posts...
}
其他两种方法:index()
和 show()
对两个角色都可用,因此无需执行任何操作。