menu

Questions & Answers

Laravel (Eloquent) query, access scope function from within subquery

I have a scope function for my user table (User.php):

public function scopeWherePaidSubscriber(Builder $query)
{
    return $query->where(....)->where(...);
}

I am trying to access this scope from a subquery looking like this:

$count = UserCalendar::whereIn('user_id', function($que) { 
        $que->select('id')->from('user')->wherePaidSubscriber();
    })->distinct('user_id')->count();

But then I noticed than I couldn't access the scope because I am not using User::wherePaidSubscriber().
The error message looks like the following:

Illuminate/Database/QueryException with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'paid_subscriber'

Eloquent probably tried to find a column named paid_subscriber since it cannot access the scope for the User table.
Is there a way for me to access the scope without having to copy paste it?

Answers(1) :

Instead of function just pass the data containing the id list of user table as an array.

User::wherePaidSubscriber()->pluck('id')->toArray();
Comments:
2023-01-11 09:00:21
Yes, this is the best method for readability, but unfortunately the best options for speed would be to copy the code from the scope. This is the best option if you don't mind the code being a bit slower :)
2023-01-11 09:00:21
Also you don't need to add select('id') since you are already using pluck('id')