繁体   English   中英

在laravel 5.2 中正确使用策略? 我不能

[英]As correctly use policies in laravel 5.2? I can not

我有一个问题,我不能在 laravel 5.2 中使用策略。

我有 2 个表,学生任务

我尝试通过更改 url 来应用策略以防止编辑任务,但我总是收到消息此操作未经授权,尽管该任务是正确的用户。

政策代码:

  <?php

    namespace App\Policies;

    use App\Models\Student;
    use App\Models\Task;

    class TasksPolicy
    {
        public function edit(Student $student, Task $tasks)
        {
            return $student->id === $tasks->student_id;
        }
    }

AuthServiceProvider.php 中的代码

<?php

    namespace App\Providers;

    use App\Models\Task;
    use App\Policies\TasksPolicy;

    class AuthServiceProvider extends ServiceProvider
    {
        /**
         * The policy mappings for the application.
         *
         * @var array
         */
        protected $policies = [
            Task::class => TasksPolicy::class
        ];

然后在 TaskController.php 文件中调用:

    public function edit($id)
    {
        $tasks = Task::findOrFail($id);
        $this->authorize('edit', $tasks);
        return view('tasks.edit', compact('tasks'));
    }

我认为代码很好,因为我已经修改了几次,但正如我之前所说,我总是收到消息尽管任务是编辑用户,但此操作未经授权

http://i.imgur.com/2q6WFb3.jpg

我究竟做错了什么? 因为我可以正确使用该政策?

你正在使用“===”这意味着双方数据和数据类型都匹配。可能你的数据是匹配的,而不是数据类型,你可以尝试使用“==”

public function edit(Student $student, Task $tasks)
    {
        return $student->id == $tasks->student_id;
    }

两件事:一是方法的名称,二是参数的顺序。 方法名称应该是 'update',而不是 'edit' - 这些是预定义的,至少在 Laravel 的后续版本中是这样。 您可能会收到授权错误,因为 Laravel 无法识别名称“edit”,因此从未定义更新策略。

参数的顺序也很重要。 当有参数传递给策略方法时,用户模型必须是第一个参数,然后是所有其他参数。

public function update(User $user, [... other objects...])

所以,你会有

update(User $user, Student $student, Task $tasks)

Laravel 将注入 Authenticated User Model 但其他对象必须直接传递。

$this->authorize('edit', $student, $tasks);

希望这会奏效。

如果您的 Student 类扩展了 User 类,您可能会认为可以在方法原型中用 Student 代替 User。 你不能那样做——那是完全不同的方法。

暂无
暂无

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

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