Posts Learn Components new Snippets new Categories Tags About Device Beast sponsor
/

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

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

Snippets 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.

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that are right for your project.

View Components

Other Code Snippets

More