How to get a single record from hasMany Relation in Laravel in the most efficient way.
$users = User::query()->addSelect([
'last_ordered_at' => Order::select("created_at")
->whereColumn('user_id', 'users.id')
->latest()
->take(1),
])->orderBy('name')->paginate();
Considering we have an eCommerce site and for each user, we want to see when did user last ordered an item.
We have a User
model and an Order
model. One user has many Orders. Using the above code you can efficiently get the last order created_at
field from the database.