Yunus Shaikh
Yunus Shaikh

Follow

Yunus Shaikh

Follow
How to get a single record from hasMany Relation in Laravel in the most efficient way.

How to get a single record from hasMany Relation in Laravel in the most efficient way.

Yunus Shaikh's photo
Yunus Shaikh
·Jan 1, 2023·

1 min read

 $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.

 
Share this