Laravel 5.4 Policy Check Always False

- 1 answer

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.


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

[email protected]

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)
    $this->authorize('view', $article->username);
    return view('', ['art' => $article]);


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



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.