Posts Learn Components Snippets Categories Tags Tools About
/

How to Eager Loading Specific Columns in Laravel

Learn how to eager loading only specific columns in Laravel to prevent unnecessary column retrieval

Created on Jul 03, 2021

1167 views

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);
  }
}

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

)