Laravel Eager Loading - Load only specific columns

In your controller you should be doing something like

App\Car::with('owner:id,name,email')->get();

Supposing that you have two models defined like below

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Car extends Model
{
    protected $table = 'car';

    public function owner()
    {
        return $this->belongsTo('App\Owner', 'owner_id');
    }
}

and

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Owner extends Model
{
    protected $table = 'owner';

    public function car()
    {
        return $this->hasMany('App\Car', 'owner_id');
    }
}

and you have two tables something like:

owners: id | name | email | phone | other_columns...

and

cars: id | owner_id | make | color | other_columns...

Credits go to the docs: eloquent-relationships#eager-loading scroll to Eager Loading Specific Columns


Also you don't need to specify getting specific columns in the model and the relationship method itself... You can do that whenever you need it... Like this:

$owners = Owner::
          with([
              'car' => function($q)
               {
                    $q->select('id', 'owner_id', 'emailid', 'name');
               },
               'bike' => function($q)
               {
                    $q->select('id', 'owner_id', 'emailid', 'name');
               }
          ])->
          get();

In this way you can also get all of the columns of the related model if you have ever needed to.


The easiest thing you can do is go by the documentation and do the following thing for getting only specific columns without any extra line of code or closure. Follow steps,

public function car(){
    return $this->hasOne('Car', 'id');
}

then when you eager load the relation select only selected columns

$owner = $this->owner
->where('id', 23)
->with('car:id,owner_id,emailid,name')   //no space after comma(, ) and id has to be selected otherwise it will give null

Hope this works, have a great day.


Make use of the select() method:

public function car() {
    return $this->hasOne('Car', 'id')->select(['owner_id', 'emailid', 'name']);
}

Note: Remember to add the columns assigned to the foreign key matching both tables. For instance, in my example, I assumed a Owner has a Car, meaning that the columns assigned to the foreign key would be something like owners.id = cars.owner_id, so I had to add owner_id to the list of selected columns;