Home / Snippets / How to Eager Loading Specific Columns in Laravel
How to Eager Loading Specific Columns in Laravel cover

How to Eager Loading Specific Columns in Laravel


2 years ago


To eager load only specific column you can specify the relationship then add the column you want it to load after specifying a column ":" separated by a comma ",".

$books = User::with('achievements:id,name,achievement_id')->get();

Do note that you have to include the "id", "foreign key" and any necessary columns as this is one of the required for this type of eager load.

Relationship Definition
The relationship is defined like usual.

namespace App\Models;

class User extends Model
  public function achievements() {
    return $this->hasMany(Achievement::class);

Inverse Relationship
For the inverse relationship, it's defined like below.

namespace App\Models;

class Achievement extends Model
  public function user() {
    return $this->belongsTo(User::class);
notion avatar

Ahmad Aziz

Week-end developer currently experimenting with web, mobile, and all things programming.






Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Post Tutorials

Learn trending tutorials for ReactJs, React Native, VueJS, NextJs, Laravel, Tailwind CSS, and Flutter development.
View Tutorials

Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that's right for your web projects
View Components

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this