为什么 Laravel 政策在 View/Blade 中不起作用?
Why Laravel Policy is not working in View/Blade?
我尝试使用政策过滤谁可以 edit/delete 我的应用程序,但它不起作用。尝试在 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
我做错了吗?尝试以管理员和创建问题的用户身份登录,但未呈现 link 到 edit/delete。
如果政策与特定问题有关,您需要传递问题的实际实例(并且不需要传递用户 class):
@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
始终是当前登录的用户。
我尝试使用政策过滤谁可以 edit/delete 我的应用程序,但它不起作用。尝试在 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
我做错了吗?尝试以管理员和创建问题的用户身份登录,但未呈现 link 到 edit/delete。
如果政策与特定问题有关,您需要传递问题的实际实例(并且不需要传递用户 class):
@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
始终是当前登录的用户。