【问题标题】:How can I make an isAuthorized() method in Eloquent ORM?如何在 Eloquent ORM 中创建 isAuthorized() 方法?
【发布时间】:2020-03-14 05:51:59
【问题描述】:

谁能逐行向我详细解释这部分?如何在 Eloquent ORM 中创建 isAuthorized(@param, @param) 方法?

class User extends Authenticatable
{
    public function isAuthorized($object, $operation)
    {
        return Db::table('role_permissions')
            ->where('object', $object)
            ->where('operation', $operation)
            ->join('user_roles', 'user_roles.role_id', '=', 'role_permissions.role_id')
            ->where('user_roles.user_id', $this->id)
            ->exists();
    }
}

【问题讨论】:

    标签: php mysql eloquent laravel-blade laravel-6


    【解决方案1】:

    我不知道我对$object$operation 的猜测是否正确,但我来了:

    <?php
    
    class User extends Authenticatable
    {
        public function isAuthorized($object, $operation)
        {
            // You are checking if the current user has access to $operation method
            // on $object. E.g. App\Http\Controllers\UserController@viewAny.
    
            // This will output a query LIKE this:
            // SELECT COUNT(`rp`.`id`)
            // FROM role_permissions rp
            // INNER JOIN user_roles ur ON ur.role_id = rp.role_id
            // WHERE `object` = 'App\\Http\\Controllers\\UserController'
            // AND `operation` = 'viewAny'
            // AND `ur`.`user_id` = 1;
            // And then it will check if the value > 0.
            return Db::table('role_permissions')
                ->where('object', $object)
                ->where('operation', $operation)
                ->join('user_roles', 'user_roles.role_id', '=', 'role_permissions.role_id')
                ->where('user_roles.user_id', $this->id)
                ->exists();
        }
    }
    
    

    如果这是它正在做的事情,您应该查看政策:https://laravel.com/docs/6.x/authorization#creating-policies

    然后使用策略: https://laravel.com/docs/6.x/authorization#via-the-user-model

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-08
      • 1970-01-01
      • 2013-01-22
      相关资源
      最近更新 更多