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

Manouher's avatar

Some of the ways to optimize eloquent query on Laravel

Hello everyone, is there a way to run a single query instead of three like this in the same model?

        $type =  Tag::with('attributs')
            ->where([['slug', '=', 'type']])
            ->get()->pluck('attributs');
        $relationship =  Tag::with('attributs')
            ->where([['slug', '=', 'relationship']])
            ->get()->pluck('attributs');
        $reason =  Tag::with('attributs')
            ->where([['slug', '=', 'reason']])
            ->get()->pluck('attributs');

0 likes
3 replies
MichalOravec's avatar
$attributs = Tag::with('attributs')
    ->whereIn('slug', ['type', 'relationship', 'reason'])
    ->get()
    ->pluck('attributs');
1 like
Manouher's avatar

Thank you very much @MichalOravec , but how to split the value of these three conditions into three difference variables, like :

       $relationship = /** where claus relationship */;
		  $type= /** where claus type */;
MichalOravec's avatar
Level 75

Use groupBy for that

$attributs = Tag::with('attributs')
    ->whereIn('slug', ['type', 'relationship', 'reason'])
    ->get()
    ->pluck('attributs')
    ->groupBy('slug');

$type = $attributs['type'] ?? [];

$relationship = $attributs['relationship'] ?? [];

$reason = $attributs['reason'] ?? [];

Docs: https://laravel.com/docs/8.x/collections#method-groupby

2 likes

Please or to participate in this conversation.