2016-03-15 100 views
0

我試圖使用Laravel 5.2身份驗證包Authorization Policies。我遵循了文檔。我似乎無法使其工作。Laravel 5.2授權政策不被閱讀

我有用戶和文檔表,文檔有user_id字段也有。

AuthServiceProvider.php

<?php 

namespace App\Providers; 

use App\Document; 
use App\User; 
use Illuminate\Contracts\Auth\Access\Gate as GateContract; 
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; 

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

    /** 
    * Register any application authentication/authorization services. 
    * 
    * @param \Illuminate\Contracts\Auth\Access\Gate $gate 
    * @return void 
    */ 
    public function boot(GateContract $gate) 
    { 
     $this->registerPolicies($gate); 
    } 
} 

DocumentPolicy.php

<?php 

namespace App\Policies; 

use App\Document; 
use App\User; 
use Illuminate\Auth\Access\HandlesAuthorization; 

class DocumentPolicy 
{ 
    use HandlesAuthorization; 

    /** 
    * Create a new policy instance. 
    * 
    * @return void 
    */ 
    public function __construct() 
    { 
     // 
    } 

    public function before($user, $ability) 
    { 
     if ($user->isSuperAdmin()) { 
      return true; 
     } 
    } 
    /** 
    * Determine if the given post can be updated by the user. 
    * 
    * @param \App\User $user 
    * @param \App\Post $post 
    * @return bool 
    */ 
    public function update(User $user, Document $document) 
    { 
     return $user->id === $document->user_id; 
    } 
} 

DocumentsController編輯功能

use Gate; 
use App\Document; 
.......some code here.... 

public function edit($id){ 
    $document = Document::findOrFail($id); 

     if (Gate::allows('update', $document)) 
     { 
      dd('a'); 
     } 
} 

正如你可以看到我把DD(「A」)來測試這一點,我不能穿過它 總是落得條件內,即使記錄我即將 編輯是不同的用戶。

回答

0

protected $policies = [ User::class => Document::class, ]; 應該

`protected $policies = [ 
    User::class => DocumentPolicy::class, 
];`