n How to get Specific Columns Using “With()” Function in Laravel Eloquent | CodimTh

Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
Category:

How to get Specific Columns Using “With()” Function in Laravel Eloquent

 

You may not always need every column from the relationships you are retrieving. For this reason, Eloquent allows you to specify which columns of the relationship you would like to retrieve:

$books = Book::with('author:id,name')->get();

 

also It can be done by passing a closure function in with() as second index of array like

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

It will only select id and username from other table. 

Remember that the primary key (id in this case) needs to be the first param in the $query->select() to actually retrieve the necessary results.*

 

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook