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


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.

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

Using the Load method

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

$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 ☕️