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

ajsmith_codes's avatar

Help with nested relationship query.

Equipment has many users. Users attach to one employee.

This query is returning 'active' for the equipment, not the employee. I need only active employees to show, but still return the equipment info if none exists.

       return Equipment::where('slug', $slug)
            ->with(['users' => function ($query) {
                $query->with(['employee' => function ($q) {
                    $q->where('active', 1);
                }]);
            }])->first();
0 likes
5 replies
kevinbui's avatar

You might want to try this:

return Equipment::where('slug', $slug)
    ->with(['users.employee' => function ($query) {
        $query->where('active', 1);
    }])->first();
tykus's avatar

The whereHas method will ensure you only retrieve Equiment where there are active employees

return Equipment::where('slug', $slug)
    ->with(['users.employee' => fn ($q) => $q->where('active', 1)])
    ->whereHas('users.employee', fn ($q) => $q->where('active', 1)
    ->first();
tykus's avatar

@ajsmith_codes In that case it is not clear what you're working with - is active on employees or on equipments

Please or to participate in this conversation.