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?

How to Get Specific or Selected Columns Using with() in Laravel Image

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:

Post::with('user')->get();

Use this:

Post::with(['user:id,name', 'comments:id,post_id,body'])->get();

This will:

  • Only fetch the id and name from the user table

  • Only fetch id, post_id, and body from the comments table

Important: Always include the foreign key (like user_id or post_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:

Post::with('user:id,name')->get();

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:

Post::with(['comments:id,post_id,body'])->get();

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:

User::with('profile:id,user_id,avatar')->get();

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:

Post::select('id', 'title')->with('user:id,name')->get();

Tags

Do you Like?