Collin Henderson
Collin Henderson

Reputation: 1154

Laravel Authorization policy not getting called

I'm having trouble getting one of my auth policies to run correctly, resulting in the authorization attempt always returning false. I'm even just forcing the function to return true for the sake of testing. I'm using Laravel 5.4, here's my policy function:

public function can_modify_or_delete(User $user, Comment $comment)
{
    return true;
}

in my AuthServiceProvider.php file I've added the CommentPolicy to my existing policy registrations.

protected $policies = [
    'App\Models\Post' => 'App\Policies\PostPolicy',
    'App\Models\Comment' => 'App\Policies\CommentPolicy',
];

oddly enough, that post policy has been working just fine. The comment one seems to either not be getting registered or not being called correctly.

In my routes:

Route::delete('/comments/{comment}', 'CommentsController@destroy');

and in the CommentsController

public function destroy(Request $request, Comment $comment)
{   
    $this->authorize('can_modify_or_delete', $comment);
    $comment->delete();

    return response(['status' => 'Comment deleted'], 200);
}

Unfortunately no matter what, that authorization check is returning false. Am I missing something? Checked pretty carefully for typos and couldn't find any. I also confirmed route model binding is working as intended so it's not a null resource issue. I tried dd() in the policy and it's not even getting called.

Upvotes: 3

Views: 6854

Answers (1)

Collin Henderson
Collin Henderson

Reputation: 1154

Wow, so it actually was a typo on my end (typical!). In my Comment model I accidentally had a lowercase models in my namespace, ie it was:

namespace App\models;

when it should have been:

namespace App\Models;

This only caught me off guard because in my controller I had:

use App\Models\Comment;

and the destroy() method injects a comment, which was actually working fine, the comment was populating as normal. It seems policy registration paths must be much more exact than a use statement.

Upvotes: 8

Related Questions