Laravel Eloquent usage > Eager loading relationships

$orders = \App\Order::with(‘user’)->get();

foreach($orders as $order){
echo $order->user->first_name;
}

The above code will execute two database queries. One to retrieve all the orders and the second to retrieve all the users tied to the orders. If you have 1000 order records, your application still executes just two queries.

Since we need only the user’s first name, we can choose to eager load it like this:

$orders = \App\Order::with(‘user:id,name’)->get();

foreach($orders as $order){
echo $order->user->first_name;
}

Advanced Laravel Eloquent usage https://blog.pusher.com/advanced-laravel-eloquent-usage/