You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Laravel的exists验证规则中使用模型Global Scope全局作用域

解决方案
  • 方案1:给exists规则传入模型类(最简单)
    Laravel的exists验证规则支持直接传入模型类作为第一个参数,此时会自动使用模型的查询构造器,触发所有已注册的全局作用域,不需要额外手动添加:
class ExpenseRequest extends FormRequest {
    protected function validationRules(): array {
        return [
            // 第一个参数替换为files表对应的模型类,例如App\Models\File
            "attachment" => Rule::exists(\App\Models\File::class, 'id')
        ];
    }
}

第二个参数为你要校验的表字段名,和原有规则逻辑保持一致即可。

  • 方案2:手动应用指定全局作用域
    如果你不想直接传入模型类,或者需要单独控制应用某一个全局作用域,可以在where回调中手动调用全局作用域的apply方法:
class ExpenseRequest extends FormRequest {
    protected function validationRules(): array {
        return [
            "attachment" => Rule::exists('files')->where(function ($query) {
                // 实例化要应用的全局作用域,调用apply方法传入查询构造器和对应模型实例
                (new \App\Scopes\CompanyScope())->apply($query, new \App\Models\File());
            })
        ];
    }
}
  • 方案3:自定义全局扩展复用规则
    如果你需要在多个验证场景下都给exists规则加该全局作用域,可以在服务提供者中扩展验证规则,一次配置多处使用:
  1. 在app/Providers/AppServiceProvider.php的boot方法中添加扩展:
use Illuminate\Validation\Rules\Exists;

public function boot()
{
    Exists::macro('withCompanyScope', function () {
        return $this->where(function ($query) {
            (new \App\Scopes\CompanyScope())->apply($query, new \App\Models\File());
        });
    });
}
  1. 在验证规则中直接调用扩展方法即可:
"attachment" => Rule::exists('files')->withCompanyScope()

内容的提问来源于stack exchange,提问作者LWlook

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 21:57:01