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

1.2K

3 years ago

0 comments

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.
<?php

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.
<?php

namespace App\Models;

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

Alaz

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

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this