How can I return the soft deleted records in the admin API's

29 Views Asked by At

I've implemented the SoftDeletes trait in my models, and I want to retrieve soft-deleted records when hitting API endpoints specifically from the admin panel.

However, I don't want these records to be visible to other roles/users.

I've tried using the withTrashed() method in my Eloquent queries, but it's not feasible to write this method in every query.

I'm using the laravel 10.

I'm expecting the global level solution for that.

1

There are 1 best solutions below

0
Kevin Bui On

Because you are providing APIs, I assume you are using an API authentication system such as sanctum.

What about applying a global scope to only show soft deleted models to certain users:

<?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()
        );
    }
}