简体   繁体   English

在Laravel中基于用户角色限制数据访问

[英]Restricting data access based on user role in laravel

I've the following scenario: I've employee role, which can add and edit only thier own data. 我有以下情形:我有员工角色,该角色只能添加和编辑自己的数据。 Also there is manager role which can view the data of all employees. 还有一个经理角色,可以查看所有员工的数据。 The data is stored in database. 数据存储在数据库中。 Where should I put the validation in this case. 在这种情况下,我应该在哪里进行验证。

You can use gates to check if a user has rights to do certain actions. 您可以使用Gates来检查用户是否有权执行某些操作。 Based on these you can fetch the data that is allowed for this user. 基于这些,您可以获取该用户允许的数据。

You can create a gate like so: 您可以这样创建一个门:

Gate::define('access-all-records', function ($user) {
    return $user->isManager; // Or any other way to find this out
});

And fetch data like this: 并像这样获取数据:

if (Gate::allows('access-all-records')) 
{
    // Fetch all records
}
else
{
    // Fetch data for this user
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM