Search code examples
phplaravellaravel-5laravel-validation

Use Model Scope in Laravel Validation Rule


I have a rule like so:

Rule::exists('tokens', 'key')
    ->where(function ($q) {
        $q->where('state', 'unused');
    })

But I'm trying to get access to the actual Token model scopes so I can just just do ->unused() and not repeat my query.

Rule::exists(\App\Models\Token::class, 'key')
    ->where(function ($q) {
        $q->unused();
    })

It appears to get a query builder, but not from the Token model.

I've tried some variation with passing the Token model in as the argument instead of the tokens table name but it just throws errors for call to undefined method.

Is there anyway to do this?


Solution

  • As you've already noticed; you've access to the query builder instead of the model. What you could do is new up a model and just use the scope directly.

    use App\Models\Token;
    
    Rule::exists('tokens', 'key')
        ->where(function ($q) {
            (new Token)->scopeUnused($q);
        });