← Back to all snippets
PHP

Optimize Eager Loading with Specific Columns and Nested Relations

Reduce memory usage and improve query performance by eager loading only necessary columns from related models and their nested relations in Laravel Eloquent.

use App\Models\User;
use App\Models\Post;

// Load users and their posts, but only the 'id' and 'title' columns for posts.
$usersWithSpecificPostData = User::with('posts:id,user_id,title')->get();

// Load users, their posts, and for each post, its category, only 'id' and 'name' for categories.
$usersWithNestedSpecificData = User::with(['posts:id,user_id,title', 'posts.category:id,name'])->get();

foreach ($usersWithNestedSpecificData as $user) {
    echo "User: ".$user->name."
";
    foreach ($user->posts as $post) {
        echo "  Post: ".$post->title." (Category: ".($post->category->name ?? 'N/A').")
";
    }
}
How it works: This snippet demonstrates how to optimize database queries by eager loading only specific columns from related models using the 'relation:id,column1,column2' syntax. This significantly reduces the amount of data retrieved from the database and improves application performance, especially for relations with many columns. It also shows how to achieve this for nested relationships, ensuring that only essential data is loaded across multiple levels of your model hierarchy.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs