How to Eager Load Specific Columns in Laravel 10
Today we will learn eager load specific columns in laravel 9 and laravel 10. We can make our query faster using the eager loading. I will show you how to get specific columns within eager load. We can use eager load while retriving the data from a relation. Let's explore an example to get specific columns with eager load.
Think you have two tables User and Post. Now Define a relation inside User Model where each user has multiple posts.
namespace App\Models;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
public function user_posts()
{
return $this->hasMany(Post::class, 'user_id', 'id');
}
}
Now eager load specific columns from User with user_post relation. Here we we will get id and title from posts table with eager load.
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\User;
class ClientController extends Controller
{
public function user_list_with_posts()
{
$user_lists = User::with('user_posts:id,title')->get()
return $user_lists;
}
}
In the above exmple we define id and title from user_posts relation while retriving the user lists. This the way we eager load specific columns in laravel eloquent relationships.
Test what you just learned with 31 interactive multiple-choice questions and instant explanations.
- Nazmul Hoque
- Updated: Jun 24, 2023
- 2 min read
- 2979
Tags
Share This:
Senior Full-Stack Engineer with 8+ years of experience building production web and mobile applications using Laravel, Next.js, TypeScript, JavaScript, React, Vue.js, MySQL, PostgreSQL, and Flutter.
You May Also Like Below Articles
Handpicked related tutorials and step-by-step developer guides to continue learning.

