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

scuissiatto's avatar

Eloquent conditional eager load

Hi I'm trying to build a query.

I 've 3 Models And 4 tables.

companies

    public function medias() {
        return $this->hasMany(CompanyMedia::class);
    }

    public function items() {
        return $this->belongsToMany(Item::class);
    }

company_medias

    public function company() {
        return $this->belongsTo(Company::class);
    }

    public function items() {
        return $this->belongsTo(Item::class);
    }

items

    public function companies() {
        return $this->belongsToMany(Company::class);
    }

company_items

pivot table

And I have a view where I show the item, with a status equals 1, with all companies in it.

And I want to select all companies that has a specific status. But only the ones who have the item that I'm showing up and a media for that item.

Right now I've tried many differents approachs but still I'm stuck here

$item = \App\Item::where('status', 1)
                                ->whereSlug($catOrItem)
                                ->with('companies')
                                ->firstOrFail();

And I've come up with a RAW query but I rather find a way to use Eloquent.

SELECT i.name, c.name, cm.path
                                FROM
                                    companies AS c
                                    LEFT JOIN company_item AS ci ON ci.company_id = c.id
                                    LEFT JOIN items AS i ON i.id = ci.item_id
                                    LEFT JOIN company_media AS cm ON cm.item_id = i.id AND cm.company_id = c.id
                                WHERE
                                    c.status = 7 AND i.status = 1 AND i.slug = 'gestao-de-perfil-empresarial-do-linkedin' AND cm.destination = 'portfolio_cover'

I would appreciate any input on that.

0 likes
3 replies
syropian's avatar

You can lazy eager load after performing the initial query.

$foo = Item::where('column', 'something');
if ($someConditional) {
    $foo->load('relation');
}
tykus's avatar

You can add constraints to eager loading also:

$item = \App\Item::where('status', 1)
    ->whereSlug($catOrItem)
    ->with(['companies' => function ($query) {
        $query->where('status', 7);
    }])
    ->firstOrFail();
1 like
scuissiatto's avatar

@syropian I can't see how this would help me :(

@tykus Yes, I can do that. But in the next step I need to query only the companies that has a media with that Item.

Please or to participate in this conversation.