How to select columns from joined tables: laravel eloquent

Finally found it.. In the ->get() you have to put the 'staff_id' like this

Vehicle::where('id',1)
            ->with(['staff'=> function($query){
                            // selecting fields from staff table
                            $query->select(['staff.id','staff.name']);
                          }])
            ->get(['id','name','staff_id']);

Since I didn't take the staff_id, it couldn't perform the join and hence staff table fields were not shown.


You can use normal join like this:

Vehicle::join('staff','vehicles.staff_id','staff.id')
         ->select(
                  'vehicles.id',
                  'vehicles.name',
                  'staff.id as staff_id',
                  'staff.name'
          )
         ->get();

Since, you can't take both id at once in a join because only one is allowed. So, you can staff's id as staff_id.

You can add vehicle id condition with where clause like:

Vehicle::join('staff','vehicles.staff_id','staff.id')
         ->where('vehicle.id',1)
         ->select(
                  'vehicles.id',
                  'vehicles.name',
                  'staff.id as staff_id',
                  'staff.name'
          )
         ->get();

Hope you understand.


The shortest and more convenient way I guess would be :

Vehicle::select('id','name','staff_id')->where('id',1)
->with('staff:id,name' )->get();

foreign key should present for selection .

Since Laravel 5.7 you can use with() like this :

with('staff:id,name' )

for granular selection.