Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 206
Rob Avatar asked Mar 07 '23 16:03

Rob


1 Answers

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);
    });
like image 136
Roy Avatar answered Mar 21 '23 09:03

Roy