Posts Learn Snippets Categories Tags 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

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

Created by

PostSrc poster

PostSrc

Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.