Home > Blockchain >  Why Laravel Policy is not working in View/Blade?
Why Laravel Policy is not working in View/Blade?

Time:03-19

I tried to filter who can edit/delete on my app using policies but it's not working. Trying to use it on blade.

QuestionPolicy.php

    const UPDATE = 'update';
    const DELETE = 'delete';

    /**
     * Check if user can update a question.
     */
    public function update(User $user, Question $question): bool
    {
        return $question->isAskedBy($user) || $user->isModerator() || $user->isAdmin();
    }

    /**
     * Check if user can delete a question.
     */
    public function delete(User $user, Question $question): bool
    {
        return ($question->isAskedBy($user) || $user->isModerator() || $user->isAdmin()) && !$user->isBanned();
    }

question.blade.php

@can(App\Policies\QuestionPolicy::UPDATE, App\Models\User::class, App\Models\Question::class)
   <a  href="#">Edit</a>
@endcan
@can(App\Policies\QuestionPolicy::DELETE, App\Models\User::class, App\Models\Question::class)
   <a  href="#">Delete</a>
@endcan

Did I do it wrong? Tried to login as admin and also the user who created the question but the link to edit/delete is not rendered.

CodePudding user response:

You need to pass the actual instance of the question (and you don't need to pass the user class) if the policy is regarding a specific question:

@can(App\Policies\QuestionPolicy::UPDATE, $question)
   <a  href="#">Edit</a>
@endcan
@can(App\Policies\QuestionPolicy::DELETE, $question)
   <a  href="#">Delete</a>
@endcan

$user in the policy is always the currently signed in user.

  • Related