Use Model Scope in Laravel Validation Rule
Asked Answered
L

1

6

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?

Luger answered 6/11, 2017 at 12:14 Comment(0)
P
7

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);
    });
Painty answered 7/6, 2018 at 13:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.