php - 如何在 Eloquent ORM 中创建 isAuthorized() 方法?

标签 php mysql eloquent laravel-blade laravel-6

谁能给我逐行详细解释一下这部分吗?如何在 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();
    }
}

最佳答案

我不知道我对 $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

关于php - 如何在 Eloquent ORM 中创建 isAuthorized() 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58921708/

相关文章:

php - session_start() 永远保持文件加载

php - 如何根据最后一个id按降序显示所选记录 MySQL PHP

php - mysql 分组并删除重复项

mysql - 如何最佳地进行 GROUP BY 并按两列进行计数?

mysql - 如何获取搜索结果中的所有列值(包括分页)

php - 查找前 5 条记录的 Eloquent 查询

laravel - 自定义验证规则使用列名称和过滤器检查是否存在

php - Laravel 队列 - 作为守护进程运行

mysql - 为什么我们需要使用外键?

php - MySQL : search function into a aggregated column by "group by"