Php 如何根据laravel中的用户角色管理控制器方法?
在我的控制器中,我需要根据用户角色的访问方法,例如,如果用户角色是admin,那么他必须访问控制器的所有方法;如果用户角色是Author,那么他可以访问index、create和show方法;如果角色是user,那么他只能访问index和show方法。您可以查看Php 如何根据laravel中的用户角色管理控制器方法?,php,laravel,roles,middleware,Php,Laravel,Roles,Middleware,在我的控制器中,我需要根据用户角色的访问方法,例如,如果用户角色是admin,那么他必须访问控制器的所有方法;如果用户角色是Author,那么他可以访问index、create和show方法;如果角色是user,那么他只能访问index和show方法。您可以查看Gates() 在App\Providers\AuthServiceProvider中添加: public function __construct() { $this->middleware('roles:Author')
Gates
()
在App\Providers\AuthServiceProvider
中添加:
public function __construct()
{
$this->middleware('roles:Author')->only(['index','show','create']);
$this->middleware('roles:User')->only(['index','show']);
}
然后在控制器的方法中create()
:
其他两种方法:
index()
和show()
对两个角色都可用,因此无需执行任何操作。检查laravel文档:您是否使用包进行角色管理?@IvankaTodorova否我为用户角色创建透视表并检查模型中的角色。感谢教授新内容,但我必须在控制器的每个方法中添加此条件,我想从构造器中管理,所以你们知道从构造器中管理哪个控制器。
Gate::define('create-post', function ($user) {
return $user->isAuthor(); //Here you should check the users role
});
if (Gate::allows('create-post')) {
// The current user can create posts...
}