PHP
Optimizing Eager Loading by Selecting Specific Columns and Nested Relationships
Learn how to enhance application performance in Laravel Eloquent by eagerly loading only necessary columns from relationships, including nested ones, to reduce memory usage.
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function address()
{
return $this->hasOne(Address::class);
}
}
class Address extends Model
{
// ...
}
class Order extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
public function items()
{
return $this->hasMany(OrderItem::class);
}
}
class OrderItem extends Model
{
// ...
}
// Eager load 'user' with only 'id' and 'name' columns,
// and 'items' with all columns.
// For 'user.address', load 'id', 'city', and 'user_id' columns.
$orders = Order::with(['user:id,name', 'items', 'user.address:id,city,user_id'])->get();
foreach ($orders as $order) {
echo $order->user->name; // Access user's name
echo " from " . $order->user->address->city . "
"; // Access user's address city
foreach ($order->items as $item) {
// Access item properties, e.g., $item->product_name
}
}
How it works: The `with()` method allows you to eager load relationships to prevent the N+1 query problem. By appending `:id,column1,column2` to a relationship name, you can specify only the columns you need, which significantly reduces memory usage and improves query performance. This technique is especially useful for large datasets and nested relationships, as shown with `user.address:id,city,user_id`, where only specific columns from the `Address` model are loaded. Always include the foreign key and primary key (usually `id`) for the relationship to function correctly.