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

p30light's avatar

How To Use groupBy in whereHas laravel

i am using Metable in my project for creating meta for orders but i have one problem i want group orders that have same email this is metable table image :

i need code like this can work :)

Order::whereHas( 'meta', function($query) {
        $query->where("key" , "gmail");
})->groupBy('meta.value')->get();

and this is meta relation that called by trait 'use Metable' in Order Model:

public function meta(): MorphMany
{
    return $this->morphMany($this->getMetaClassName(), 'metable');
}

Thanks

0 likes
8 replies
bugsysha's avatar

Have you tried passing a closure to groupBy method? Same as whereHas.

p30light's avatar

Yes but not worked I think the problem is morph!

bugsysha's avatar

Can you tell what you need that query to result to? Cause you can try something like

Meta::with('orders')->groupBy('value')->get();

Or even better

Meta::with('orders')->where('key', 'gmail')->get();

Just one thing, you should remove that screenshot from your initial post since it looks like real data.

p30light's avatar

i got this error there is any wat get metas from Order class and grouping them?

i have many orders that have same meta like gmail i want grouping them with meta and get orders that have same meta like gmail to use in backpack laravel crud

bugsysha's avatar

Just add that relationship and you are all set to go.

bugsysha's avatar

Should be something like

    public function orders(): MorphTo
    {
        return $this->morphTo();
    }
p30light's avatar

it works fine but i use this code:

Meta::with('metable')->where('key','gmail')->groupBy('value')->get();

but now how can i limit orders? for example just order that belongs to specific user or any where closure i try this but not worked

$this->data['emails'] = Meta::with(['metable' => function($query) {
            $query->where('user_id' , 2);
        }])->where('key','gmail')->groupBy('value')->get();
and nothing changed got all orders !
p30light's avatar
p30light
OP
Best Answer
Level 1

finaly i found the solution new feature of laravel 5.8 is a closure handled my problem whereHasMorph()

and this is working code:

$this->data['emails'] = Meta::whereHasMorph('metable' , Order::class , function($query) {
            $query->where('user_id' , 2);
})->where('key','gmail')->groupBy('value')->get();
Tnx Every One
1 like

Please or to participate in this conversation.