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

MarcelWeidum's avatar

Laravel lazy eager load only fields eloquent relation

For inertiajs I try to only load certain fields in collection that I pass to the view.

public function edit(Order $order)
{
    $this->authorize('update', $order);

    $order_data = $order->load([
        'hours' => function ($q) {
            $q->get(['id']); // select only id field
        }
    ])->only(['id', 'title', 'description', 'hours']);

    return Inertia::render('Admin/Orders/Edit', [
        'order' => $order_data
    ]);
}

I have this code, of the order I only get those fields, but the hours that belongs to the order I only want the id. This is not working. Also, $q->select(['field']); isn't working.

Someone knows how to do this?

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

You will also need the foreign key on the hours table that relates to the Order

 $order->load('hours:id,order_id')
1 like

Please or to participate in this conversation.