Laravel

/

Dary nazar

How to improve Laravel eager loading by selecting specific columns with the with() method

If you've been building Laravel apps for a while, you've probably run into the classic N+1 query problem. Lazy loading is convenient, but it kills performance when you loop through a collection and access relationships one by one.

If you've been building Laravel apps for a while, you've probably run into the classic N+1 query problem. Lazy loading is convenient, but it might kill the performance when you loop through a collection and access relationships one by one.

The fix? Eager loading with with(). But here's the thing most tutorials skip: by default, with('user') loads every single column from the users table. With APIs, mobile apps, and large datasets, this is a silent performance killer.

What is lazy loading? (Quick refresher + the N+1 problem)

When you access a relationship as a property for the first time, Laravel runs a lazy query:

<?php 

$posts = Post::all();

foreach ($posts as $post) {
    echo $post->user->name;
}

This fires 1 query for posts + N queries for users → disaster at scale.

Eager loading fixes it, since it performs 2 queries total: posts + all users.

<?php

$posts = Post::with('user')->get();

This is great…. but with('user') still pulls the entire users table row, and this can be done better.

Eager loading specific columns

Laravel lets you specify exactly which columns to load using the super-clean colon syntax:

<?php

$posts = Post::with([
    'user:id,name,email',
    'category:id,name,slug',
])->get();

That's it! Laravel will only select id, name, and email from the users table.

Why selective column eager loading works well

By telling Laravel exactly which columns to fetch from related models (e.g., with('user:id,name,email'), you unlock serious performance and efficiency gains.

Much smaller payload

Especially critical for APIs loading full user models often means sending dozens of unnecessary columns (remember_token, email_verified_at, timestamps, etc.). Smaller payloads = faster API responses, lower bandwidth costs, and happier mobile users who aren't waiting on bloated data.

Less memory pressure in PHP

When Laravel hydrates full Eloquent models for hundreds or thousands of records, PHP has to allocate memory for every column, even the ones you ignore. By loading only 3–5 fields, you dramatically reduce memory usage, helping you avoid those dreaded "Allowed memory size exhausted" errors on production servers during peak traffic.

Less data transferred over the wire

Every byte counts in 2026: slower networks, metered mobile data, CDNs charging by GB. Sending only what your frontend actually needs reduces latency, improves Time to First Byte (TTFB), and makes your app feel snappier worldwide.

Always include the foreign key / primary key

If you forget the id (or custom primary key), the relationship won't match up correctly, you'll get empty or null relations.

Correct example (belongsTo):

<?php

Post::with('user:id,name,email');

Wrong example:

<?php

Post::with('user:name,email');

Another example where it has been setup correctly:

<?php

public function index()
{
    return PostResource::collection(
        Post::query()
            ->with([
                'user:id,name,email,profile_photo_url',
                'category:id,name,slug',
                'tags:id,name',             
            ])
            ->latest()
            ->paginate()
    );
}

Your JSON response is now tiny compared to dumping full user models.

An alternative: the closure way

Sometimes you don’t just want to select specific columns, you also need to add conditions, ordering, limits, or even apply model scopes to the related query. That’s where the closure syntax shines. It gives you the full power of the query builder while still letting you keep things lean.

<?php

$posts = Post::with([
    'user' => function ($query) {
        $query->select('id', 'name', 'email', 'profile_photo_url')
              ->where('active', true)
              ->whereNotNull('profile_photo_url');
    },
    'comments' => function ($query) {
        $query->select('id', 'post_id', 'body', 'created_at')
              ->latest()
              ->limit(5);
    },
    'comments.user' => function ($query) {
        $query->select('id', 'name');
    },
])->latest()->paginate();

Conclusion

Selective eager loading isn't just a "nice-to-have". In real apps with real users, it's often one of the quickest ways to 2–10× faster APIs and happier everything. Try measuring your own endpoints before/after, the numbers will convince you instantly.

/

BLOG

/

BLOG

/

BLOG

Laravel

/

Jan 5, 2026

How Laravel config and environment variables should be used together

Today, we’re diving into something that might seem small but is actually incredibly important in your Laravel journey: how to properly use Laravel’s config files together with your .env variables. This is one of those topics that can really level up the way you structure and manage your application, especially if you’re building apps that need to run in different environments (development, staging, production, etc.).

Laravel

/

Jan 5, 2026

How Laravel config and environment variables should be used together

Today, we’re diving into something that might seem small but is actually incredibly important in your Laravel journey: how to properly use Laravel’s config files together with your .env variables. This is one of those topics that can really level up the way you structure and manage your application, especially if you’re building apps that need to run in different environments (development, staging, production, etc.).

Laravel

/

Jan 5, 2026

How Laravel config and environment variables should be used together

Today, we’re diving into something that might seem small but is actually incredibly important in your Laravel journey: how to properly use Laravel’s config files together with your .env variables. This is one of those topics that can really level up the way you structure and manage your application, especially if you’re building apps that need to run in different environments (development, staging, production, etc.).

Laravel

/

Jan 3, 2026

How to prevent performance issues in Laravel by using eager loading

In this guide, we’ll look at why eager loading should be considered a default practice when working with Eloquent models. It helps prevent hidden performance issues, reduces unnecessary database queries, and makes your application scale more predictably as it grows.

Laravel

/

Jan 3, 2026

How to prevent performance issues in Laravel by using eager loading

In this guide, we’ll look at why eager loading should be considered a default practice when working with Eloquent models. It helps prevent hidden performance issues, reduces unnecessary database queries, and makes your application scale more predictably as it grows.

Laravel

/

Jan 3, 2026

How to prevent performance issues in Laravel by using eager loading

In this guide, we’ll look at why eager loading should be considered a default practice when working with Eloquent models. It helps prevent hidden performance issues, reduces unnecessary database queries, and makes your application scale more predictably as it grows.

PHP

/

Jan 1, 2026

Why type hinting is extremely important in programming

Type hinting is a programming feature that allows developers to specify the data types of variables, arguments, and return types in functions or methods. It is a feature that has been introduced in many programming languages in recent years, including PHP, Python, and Java. In this blog post, we will discuss why type hinting is important, the advantages and disadvantages of using it, how we can implement it in our code, and see some examples

PHP

/

Jan 1, 2026

Why type hinting is extremely important in programming

Type hinting is a programming feature that allows developers to specify the data types of variables, arguments, and return types in functions or methods. It is a feature that has been introduced in many programming languages in recent years, including PHP, Python, and Java. In this blog post, we will discuss why type hinting is important, the advantages and disadvantages of using it, how we can implement it in our code, and see some examples

PHP

/

Jan 1, 2026

Why type hinting is extremely important in programming

Type hinting is a programming feature that allows developers to specify the data types of variables, arguments, and return types in functions or methods. It is a feature that has been introduced in many programming languages in recent years, including PHP, Python, and Java. In this blog post, we will discuss why type hinting is important, the advantages and disadvantages of using it, how we can implement it in our code, and see some examples

Laravel