如何在模板组件中使用授权策略
新创建了一个绑定文章模型的授权策略。
<?php
namespace App\Policies;
use App\Models\Article;
use App\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;
class ArticlePolicy
{
use HandlesAuthorization;
/**
* before 策略过滤器
* --
* $user 当前用户
* $ability 当前触发策略
*/
public function before($user, $ability)
{
// 如果是超级管理员,一切通过
if ($user->id == '1')
{
return true;
}
}
/**
* Determine whether the user can view any models.
*
* @param \App\Models\User $user
* @return \Illuminate\Auth\Access\Response|bool
*/
public function viewAny(User $user)
{
//
}
/**
* Determine whether the user can view the model.
*
* @param \App\Models\User $user
* @param \App\Models\Article $article
* @return \Illuminate\Auth\Access\Response|bool
*/
public function view(User $user, Article $article)
{
//
}
/**
* Determine whether the user can create models.
*
* @param \App\Models\User $user
* @return \Illuminate\Auth\Access\Response|bool
*/
public function create(User $user)
{
return $user->id == '1';
}
/**
* Determine whether the user can edit the model.
*
* @param \App\Models\User $user
* @param \App\Models\Article $article
* @return \Illuminate\Auth\Access\Response|bool
*/
public function edit(User $user, Article $article)
{
return $user->id == $article->author_id;
}
/**
* Determine whether the user can destroy the model.
*
* @param \App\Models\User $user
* @param \App\Models\Article $article
* @return \Illuminate\Auth\Access\Response|bool
*/
public function destroy(User $user, Article $article)
{
return $user->id == $article->author_id;
}
/**
* Determine whether the user can restore the model.
*
* @param \App\Models\User $user
* @param \App\Models\Article $article
* @return \Illuminate\Auth\Access\Response|bool
*/
public function restore(User $user, Article $article)
{
//
}
/**
* Determine whether the user can permanently delete the model.
*
* @param \App\Models\User $user
* @param \App\Models\Article $article
* @return \Illuminate\Auth\Access\Response|bool
*/
public function forceDelete(User $user, Article $article)
{
//
}
}
但是这个策略中,create 方法是要放到模型组件中去使用。模板组件的视图里使用
@can(‘create’, $user) 报错找不到$user.