简体   繁体   English

如何根据 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']);
}

In my controller i want access methods as per users role for eg if user role is admin then he has to access all methods of controller, if user role is Author then he has access of index,create and show method and if role is User then he has only access of index and show method.在我的控制器中,我希望根据用户角色访问方法,例如,如果用户角色是管理员,则他必须访问控制器的所有方法,如果用户角色是作者,则他可以访问索引、创建和显示方法,如果角色是用户,则他只能访问 index 和 show 方法。

You can take a look at Gates ( docs ).你可以看看Gates文档)。

In your App\\Providers\\AuthServiceProvider add:在您的App\\Providers\\AuthServiceProvider添加:

Gate::define('create-post', function ($user) {
    return $user->isAuthor(); //Here you should check the users role
});

And then in your controller's method create() :然后在您的控制器方法create()

if (Gate::allows('create-post')) {
    // The current user can create posts...
}

The other two methods: index() and show() are available to both roles so there's no action required.另外两个方法: index()show()对这两个角色都可用,因此不需要任何操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Laravel 中检查身份验证用户角色? - How can I check auth user role in laravel? Laravel 6:如何将 user_id 和 role_id(s) 发送到控制器,以同步 user_role 数据透视表? - Laravel 6: how do I send user_id with role_id(s) to controller, in order to sync user_role pivot table? 如何通过Laravel中的URL访问控制器方法? - How can I access controller methods via url in Laravel? 我如何在laravel控制器中一次执行多个方法 - How can I execute multiple methods at once in a laravel controller Laravel3:如何将post方法转发给控制器的动作? - Laravel3: How can I forward post methods to action of controller? 不同的控制器取决于用户角色 - Laravel 5.1 - Different controller depending on user role - Laravel 5.1 在Laravel中管理多个角色 - Manage multiple Role in laravel 如何使用附加 function 将用户 ID 和角色 ID 附加到 laravel 中的 pivot 表? - How can I attach the user id and role id to the pivot table in laravel using attach function? 我如何在注册过程中为用户分配角色? (委托)(Laravel 5.1) - How i can assign a role to a user during signup? ( Entrust ) ( Laravel 5.1 ) 如何根据 Laravel 8 中的用户角色或权限重定向到不同的视图? - How can I redirect to different views based on user role or privilege in Laravel 8?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM