Posts Learn Components Snippets Categories Tags Tools About
/

How to Specify Specific Columns When Eager Loading Relationship in Laravel

Learn how to specify the columns when eager loading a realtionship in laravel using the "with" or "load" method.

Created on Oct 08, 2021

253 views

To specify specific columns when eager loading relationship in Laravel you can pass in a closure to the "with" and "load" method and then only "select" the columns that you need for the relationship from within the closure. 

Query Post Model With Specific Column


To only query the "id" and "username" columns of the relationship model, you can write the code below.
<?php

Post::query()
    ->with(['user' => function($query) {
        $query->select(['id', 'username']);
    }])
    ->get();

Using the Load method


If you are using the "load" method then you can write it as follows.
<?php

$post = Post::first();

$post->load(['user' => function($query) {
    $query->select(['id', 'username']);
}]);

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

)