我已经在模型中实现了 SoftDeletes 特征,并且我想在专门从管理面板访问 API 端点时检索软删除记录。
但是,我不希望这些记录对其他角色/用户可见。
我尝试在 Eloquent 查询中使用 withTrashed() 方法,但在每个查询中都编写此方法是不可行的。
我正在使用 laravel 10。
我期待全球层面的解决方案。
因为您提供 API,所以我假设您正在使用 API 身份验证系统,例如 sanctum。
如何应用全局范围来仅向某些用户显示软删除的模型:
<?php
namespace App\Models\Scopes;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
class WithSoftDeletedScope implements Scope
{
/**
* Apply the scope to a given Eloquent query builder.
*/
public function apply(Builder $builder, Model $model): void
{
$builder->when(
auth()->tokenCan('view trashed models'),
fn ($query) => $query->withTrashed()
);
}
}