D. Cichowski
D. Cichowski

Reputation: 777

Laravel: Use scope from related model to filter results

TLTR:

How to get a Collection of from one model (Users) using scope method from another (UserSubscriber)? Models are in one-to-one relation.

More about:

I have two model related one-to-one:

Second model is only for some users that has extended, specific role (subscribers in this case)

User model:

class User extends \Sentinel\Models\User
{
    public function subscriber()
    {        
        return $this->hasOne('App\Models\UserSubscriber', 'user_id');
    }       
}

UserExtended model:

class UserSubscriber extends Model
{  
    public function user()
    {        
        return $this->belongsTo('App\Models\User', 'user_id');
    }        

    public function scopeLangSubscribers($query, $langCode)
    {
        $query->where('languages_subscribed', 'LIKE', '%' . $langCode . '%');
    }    
}

The goal is:

Get a Collection of Users using scope from UserSubscriber.

(Without rewriting this scope method to User model.)

Where I stuck:

            $users = User::with(['subscriber' => function ($query) use ($lang) {
                $query->langSubscribers($lang);
            }])->get();

This returns me collection of all users with 'subscriber' set as null for some of them.

I've tried to filter them, but:

'subscriber' is not a column, so I can't do:

->whereNotNull('subscriber')

How can I accomplish this?

Edit:

Alternatively, maybe there is a way to convert one collection (of subscribers) to another (users) afterretrieving this first, which can be done very aesy and clean:

$usersSubscribers = UserSubscriber::langSubscribers($lang)->get();

Upvotes: 3

Views: 15408

Answers (1)

chanafdo
chanafdo

Reputation: 5124

Use whereHas instead.

$users = User::with('subscriber')->whereHas('subscriber', function    ($query) use ($lang) {
    $query->langSubscribers($lang);
})->get();

Upvotes: 5

Related Questions