2016-03-31 35 views
4

我有一個問題,我不能在laravel 5.2中使用策略。正確使用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

我在做什麼錯?我可以正確使用這項政策嗎?

+0

我不t認爲它意味着在兩個模型之間使用。其中一個*必須是'用戶'模型。 – Hkan

+0

嗨,表用戶使用它爲其他用戶,所以我必須使用學生表(我使用multi-auth laravel 5.2)。 –

+0

如果你在'edit()'方法中使用'dd($ student-> id,$ tasks-> student_id)',你會得到什麼? –

回答

0

您正在使用「===」,這意味着兩側數據和數據類型將match.May將您的數據是匹配的,而不是數據類型,您可以嘗試使用「==」

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

同樣的結果。感謝您的幫助。 –

+1

And ===是文檔中推薦的比較運算符。 –

+0

這不是一個很大的問題什麼文件說,事實是我們使用運營商,因爲我們需要 –