简体   繁体   中英

Why Laravel Policy is not working in View/Blade?

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 class="text-sm font-light text-gray-600" href="#">Edit</a>
@endcan
@can(App\Policies\QuestionPolicy::DELETE, App\Models\User::class, App\Models\Question::class)
   <a class="text-sm font-light text-gray-600" 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.

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 class="text-sm font-light text-gray-600" href="#">Edit</a>
@endcan
@can(App\Policies\QuestionPolicy::DELETE, $question)
   <a class="text-sm font-light text-gray-600" href="#">Delete</a>
@endcan

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM