Search code examples
laravelpolicy

Laravel 5.4 policy check always false


So I have created a policy and registered it in the AuthServicePRovider, but it always returns false. It is my first time working with policies so I am sure I am doing it wrong, but following a few examples, nothing has worked for me.

AuthServiceProvider

protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
        Article::class => ArticlePolicy::class,
    ];

ArticleController@show

public function show($article_id) I 
{
    $article = DB::table('pjt_article as a')
        ->join('pjt_categories_article as c', 'a.cate_id', '=', 'c.cate_id')
        ->where('article_id', $article_id)
        ->first();
    $this->authorize('view', $article->username);
    return view('admin.content.show-article', ['art' => $article]);
}

ArticlePolicy

public function view(Admin $admin, Article $article)
{
    return $admin->id == $article->username;
}

I'm try == and === but not working

This image error 403

enter image description here


Solution

  • Your policy is mapped to a Model classname. You would have to have a model instance to be able to do this. Your query is using Query Builder directly and not returning a Model instance.

    $article = Article::....->first();
    

    For authorize you want to pass the resource you want to authorize to authorize not the attribute on a resource you will eventually check in the policy:

    $this->authorize('view', $article->username);
    
    // to
    
    $this->authorize('view', $article);
    

    The way the Gate knows to even use a policy for a resource is because of the type of the object passed, or if passed a classname.