如何在管理API中返回软删除的记录

问题描述 投票:0回答:1

我已经在模型中实现了 SoftDeletes 特征,并且我想在专门从管理面板访问 API 端点时检索软删除记录。

但是,我不希望这些记录对其他角色/用户可见。

我尝试在 Eloquent 查询中使用 withTrashed() 方法,但在每个查询中都编写此方法是不可行的。

我正在使用 laravel 10。

我期待全球层面的解决方案。

laravel eloquent laravel-10 soft-delete
1个回答
0
投票

因为您提供 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()
        );
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.