This forum has moved to a new location and is in read-only mode. Please visit talk.octobercms.com to access the new location.

ax2to
ax2to

How to extend User class with scope. I want to extend class user with scope "hasLocation":

For example:

User::hasLocation()->get();

public hasLocation($query){
    return $query->where('has_location',1);
}

I want create hasLocation scope

Last updated

axomat
axomat

Have you seen this video? Post more details if it does not answer your question.

Scott
Scott

This might do what you need, haven't tested it though

public function boot()
{
    User::extend(function($model) {
        $model->addDynamicMethod('scopeHasLocation', function($query) {
            return $query->where('has_location', 1);
        });
    });
}
ax2to
ax2to

Thanks for your replies. Scott I will try that.

ax2to
ax2to

Unfortunately this not work.

I have this error:

Call to undefined method October\Rain\Database\QueryBuilder::hasLocation()
throw new BadMethodCallException("Call to undefined method {$className}::{$method}()");

Maybe scope not work with addDynamicMethod.

Back to the question, how to add scope method to a Class using extend method.

I think Scott should be close.

Last updated

Scott
Scott

ax2to, i just tested my method and it works. You're placing this code inside the boot() function of your Plugin.php file, correct? Can paste your code at http://kopy.io and show me your Plugin.php file and the code of where you're trying to use the new scope?

Last updated

ax2to
ax2to

My apologies!. The error is mine.

I'm extend "RainLab\User\Models\User" but in the call are using "October\Rain\Auth\Models\User", replace corrected class and it is done.

Thanks for your help.

Mohsin
Mohsin

Umm what is it useful for? I couldn't make sense of what extending a user class with scope means.

chris10207
chris10207

@Moshin: i guess it means that you can filter the list of user with this scope. you can get a user list who has the field location set to true.

Mohsin
Mohsin

Ok gotcha. It makes sense now.

1-10 of 10

You cannot edit posts or make replies: the forum has moved to talk.octobercms.com.