我正在为模型 todo 创建一个策略来授权用户角色,然后为
create()
、update()
等模型函数设置自定义访问权限。正如 Laravel 文档中所写,我们可以使用以下命令为 todo 模型创建策略: php artisan make:policy todoPolicy --model=todo
。
当我们使用 modelname + Policy 作为位于 App\Policies 文件夹中的策略名称时,Laravel 会自动为模型注册它们,就像我们使用 todoPolicy 来表示 todo 模型一样。
另外,为了检查此策略是否有效,我在 todoPolicy 文件中为
return true;
函数设置了 create()
,并在组件的 add 函数中调用 $this->authorize('create,' todo::class);
进行测试。
但是总是返回403,不是授权页面。我的代码有什么问题吗?
组件/控制器
namespace App\Livewire\Elements\Todolist;
use Livewire\Component;
use App\Models\todo;
class Todolist extends Component
{
public $description;
public function done($id) {
sleep(0.5);
todo::where('id',$id)->first()->update([
'is_done' => true,
]);
}
public function restore($id) {
sleep(0.5);
todo::where('id',$id)->first()->update([
'is_done' => false,
]);
}
public function delete($id) {
sleep(0.5);
todo::where('id',$id)->first()->delete();
}
public function add(todo $todo) {
$this->authorize('create',$todo);
$this->validate([
'description' => ['required','max:128'],
]);
sleep(0.5);
todo::create([
'user_id' => session('user_id'),
'description' => $this->description,
]);
$this->reset();
}
public function render()
{
return view('livewire.elements.todolist.todolist',[
'todos' => todo::orderBy('is_done','ASC')->orderBy('created_at','DESC')->get(),
]);
}
}
待办政策
namespace App\Policies;
use App\Models\User;
use App\Models\todo;
use Illuminate\Auth\Access\Response;
class todoPolicy
{
/**
* Determine whether the user can view any models.
*/
public function viewAny(User $user): bool
{
}
/**
* Determine whether the user can view the model.
*/
public function view(User $user, todo $todo): bool
{
}
/**
* Determine whether the user can create models.
*/
public function create(User $user): bool
{
return true;
}
/**
* Determine whether the user can update the model.
*/
public function update(User $user, todo $todo): bool
{
//
}
/**
* Determine whether the user can delete the model.
*/
public function delete(User $user, todo $todo): bool
{
//
}
/**
* Determine whether the user can restore the model.
*/
public function restore(User $user, todo $todo): bool
{
//
}
/**
* Determine whether the user can permanently delete the model.
*/
public function forceDelete(User $user, todo $todo): bool
{
//
}
}
我尝试过手动注册策略,但没有改变任何东西。
问题是,当我们想要返回 true 策略函数而不向其传递模型时,我们应该像这样使其可选:
public function create(?User $user): bool
{
return true;
}