Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

tomasosho's avatar

how to list only users with `vendor role` that are subscribed

How do i check and list only users with vendor role that are subscribed.

Users with vendor role renders foreach...

$vendors = User::whereHas(
                    'roles', function($q){
                        $q->where('name', 'vendor')->inRandomOrder();
                    }
                )->paginate(3);

Subscription checker

if (auth()->user()->subscribedToPlan(['PLN_uqicl68u6pq9qyl', 'PLN_pmgc1t08ff3kwwr', 'PLN_pklwcpsl3s6odjf'], 'default')) {
                        
#######
             }
0 likes
5 replies
tykus's avatar

If you want to use the same query to find the users who are vendor and subscribed, then you will need to unpack the logic of your subscribedToPlan method and convert it to Query Builder.

tykus's avatar
tykus
Best Answer
Level 104

You can load *all users having the vendor role (as you describe above), and then filter those results in PHP, however, you also want to paginate, in which case, you might get 3 results, or 2, or 1, or 0 because limit has already happened on the query before PHP has filtered the results. Say there was no paginate, you could do the following (assuming the subscribedToPlan method returns truthy/falsey value):

$vendors = User::whereHas('roles', function($q) {
    $q->where('name', 'vendor');
})->get()->filter->subscribedToPlan(['PLN_uqicl68u6pq9qyl', 'PLN_pmgc1t08ff3kwwr', 'PLN_pklwcpsl3s6odjf'], 'default');

This operation will filter the entire result of the Users who are vendors. The problem is the potential size of the dataset which PHP must operate on, and you only want 3!?!

(Aside, the inRandomOrder makes no sense to me there in the whereHas closure)

tomasosho's avatar

Thanks, the pagination was just to limit my returned $vendors. I just limited the query.

$vendor = User::whereHas('roles', function($q) {
                    $q->where('name', 'vendor')->limit(6);
                })->get()->filter->subscribedToPlan(['PLN_uqicl68u6pq9qyl', 'PLN_pmgc1t08ff3kwwr', 'PLN_pklwcpsl3s6odjf'], 'default');
tykus's avatar

That limit makes no sense (in that position) for the same reason inRandomOrder made no sense. If you want to limit the User, then move it outside the closure:

$vendor = User::whereHas('roles', function($q) {
    $q->where('name', 'vendor');
})->limit(6)->get()
    ->filter->subscribedToPlan(['PLN_uqicl68u6pq9qyl', 'PLN_pmgc1t08ff3kwwr', 'PLN_pklwcpsl3s6odjf'], 'default');

I should say, this is not the most efficient way to produce a result, and neither are you guaranteed any Users because the filter operation might remove anywhere between 0 and 6 of the results!!!

Please or to participate in this conversation.