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.

