How to Get Specific or Selected Columns Using with() in Laravel
When working with large datasets in Laravel, eager loading relationships is a great way to reduce the number of queries. But did you know you can limit the columns you fetch during eager loading to further optimize performance?

Learn how to improve Laravel performance by eager loading relationships with only the columns you need. Reduce query size, save memory, and boost speed with this powerful Eloquent tip.
By default, Laravel's with()
eager loads all columns of a related model — but you can optimize this by selecting only the columns you need.
Instead of this:
Use this:
This will:
Only fetch the
id
andname
from theuser
tableOnly fetch
id
,post_id
, andbody
from thecomments
table
Important: Always include the foreign key (like
user_id
orpost_id
) when selecting specific columns in relationships, or Laravel won't know how to join the models.
Why use this?
Reduces memory usage
Speeds up API responses
Makes queries lighter and faster
Keeps your data clean and lightweight
Perfect for performance-critical applications and APIs.
🔍 Tip from the Laravel Docs
Frequently Asked Questions (FAQ)
How do I select specific columns when using with()
in Laravel?
You can pass an array to the with()
method specifying the columns you want:
This will eager load the user
relation, but only fetch the id
and name
columns.
Can I eager load relationships with selected fields in Laravel?
Yes! Laravel allows you to load related models with only selected fields using:
Just make sure to include the foreign key (post_id
in this case) for the relationship to work.
What's the best way to optimize eager loading in Laravel?
To optimize eager loading:
Only load relationships you actually need
Select only necessary columns
Use pagination if dealing with large datasets
Why is my Laravel query using with()
slow?
If you're not selecting specific columns, Laravel loads all fields by default. This increases memory usage and slows down your app. Use selected fields like this:
Can I use with()
and select()
together in Laravel?
Yes, but they serve different purposes. Use select()
on the base model, and with()
for relationships: