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

robinsonryan's avatar

Adding select() breaks Eloquent query

I have two tables inventory_items and medications that both have a name column. I'm creating a query builder and need to alias the name column on medications.

I've built my query, but if I add the select() method, it fails to load the related model. When the select() method is added to the builder, this is what I see in the DB log for the related model query:

//fails to load the related models
select * from `devices` where 0 = 1 and `devices`.`deleted_at` is null

vs. this when I remove the select

//correctly loads the related models
select * from `devices` where `devices`.`id` in (3799) and `devices`.`deleted_at` is null

Here is my query builder code (with the select()):

//$subscriber = Subscriber model passed in via function parameter

$items = InventoryItem::with('device')
            ->select('inventory_items.id', 'inventory_items.name', 'inventory_items.rfid', 'inventory_items.expiration_date', 'medications.name as medication_name')
            ->join('medications', 'medications.id', '=', 'inventory_items.medication_id')
            ->where('inventory_items.client_id', $subscriber->client_id)
            ->where('inventory_items.expiration_date', '<', Carbon::now())
            ->orderBy('inventory_items.expiration_date', 'asc')
            ->get();

Why does adding the select() method cause the related model query to fail?

0 likes
2 replies
tykus's avatar
tykus
Best Answer
Level 104

It looks like an InventoryItem belongs to a Device; but you do not select the device_id to allow Eloquent eager-load the device relation:

->select('inventory_items.id', 'inventory_items.name', 'inventory_items.device_id', 'inventory_items.rfid', 'inventory_items.expiration_date', 'medications.name as medication_name')

robinsonryan's avatar

Problem solved. Thanks @tykus! I knew it was going to be some easy thing I was overlooking.

Please or to participate in this conversation.