Igor Simic
4 years ago

How to select specific fields when using with function in eloquent Laravel?

Joining connected tables using with() function in eloquent is really useful and easy, but this will give you all fields from these tables which in many cases we do not need. So, how do we select only specific columns from tables when using with() function in eloquent?

To use with() command Laravel models need to be already connected (one to many, many to many...), if they are not please check that first.
Let's take a look to example where we want to query published posts with author (id, name, slug), authordetails (photo) and tags (id, name) but we want to get only specific fields from connected tables and to just get number of comments (but not comments data)

$post = Post::where('published','=', 1)->with([
                'author' => function($query){
                        // selecting fields from authordetail table
                    // selecting fields from author table
                    // selecting fields from  tags table
    // selecting fields from post table
    // get only number of comments
    // take 20 records in pagination style