Home / Snippets / How to Specify Specific Columns When Eager Loading Relationship in Laravel
How to Specify Specific Columns When Eager Loading Relationship in Laravel cover

How to Specify Specific Columns When Eager Loading Relationship in Laravel

312

3 years ago

0 comments

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']);
}]);
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this