Laravel 10如何在Admin API全局返回软删除记录且仅管理员可见
全局控制软删除记录的可见性(仅管理员可查看)
方法一:自定义全局作用域(推荐)
创建全局作用域类,根据当前用户角色自动决定是否包含软删除记录:
// app/Scopes/AdminIncludeTrashedScope.php <?php namespace App\Scopes; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Scope; use Illuminate\Support\Facades\Auth; class AdminIncludeTrashedScope implements Scope { public function apply(Builder $builder, Model $model) { // 根据实际权限逻辑调整,比如用角色系统可改为 Auth::user()->hasRole('admin') if (Auth::check() && Auth::user()->is_admin) { $builder->withTrashed(); } // 非管理员无需额外处理,SoftDeletes trait已默认过滤软删除记录 } }
在需要应用的模型中注册该全局作用域:
// app/Models/YourModel.php <?php namespace App\Models; use App\Scopes\AdminIncludeTrashedScope; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class YourModel extends Model { use SoftDeletes; protected static function booted() { static::addGlobalScope(new AdminIncludeTrashedScope); } }
补充说明
- 若管理员需临时查看仅未删除的记录,可在查询中调用
withoutTrashed()覆盖全局作用域 - 所有继承该模型的子类会自动应用此规则
方法二:路由中间件控制(针对管理员API分组)
如果仅需在管理员面板的API路由中生效,可通过中间件全局注入查询规则:
- 创建中间件:
// app/Http/Middleware/AdminIncludeTrashed.php <?php namespace App\Http\Middleware; use Closure; use Illuminate\Database\Eloquent\Builder; use Illuminate\Support\Facades\Auth; class AdminIncludeTrashed { public function handle($request, Closure $next) { if (Auth::check() && Auth::user()->is_admin) { Builder::globalScope('admin_include_trashed', function (Builder $builder) { $builder->withTrashed(); }); } return $next($request); } }
- 在
app/Http/Kernel.php中注册中间件别名:
protected $routeMiddleware = [ // ...其他中间件 'admin.trashed' => \App\Http\Middleware\AdminIncludeTrashed::class, ];
- 给管理员API路由组绑定该中间件:
// routes/api.php Route::prefix('admin')->middleware(['auth:sanctum', 'admin.trashed'])->group(function () { // 管理员专属API路由 Route::get('posts', [PostController::class, 'index']); // ...其他路由 });
方法三:模型boot方法直接写入(快速实现)
若不想单独创建作用域类,可直接在模型的 booted 方法中添加匿名全局作用域:
// app/Models/YourModel.php protected static function booted() { static::addGlobalScope('admin_trashed', function (Builder $builder) { if (Auth::check() && Auth::user()->is_admin) { $builder->withTrashed(); } }); }
内容的提问来源于stack exchange,提问作者Harshil Patanvadiya
相关产品推荐
相关产品推荐

