Skip to content
Advertisement

Getting specific column in Laravel relation returning empty array

I want to get specific column from Model relation in Laravel, but the relation model returning empty array.

Eloquent Query

$medicines = Medicine::with(['weightage' => function($query) {
            $query->select('name');
        }])->get(['name', 'description']);

Medicine Modal

public function weightage()
{
    return $this->hasMany('AppMedicineWeightage', 'medicine_id');
}

Advertisement

Answer

You always need to also select the primary and foreign keys of the table to make the relation work:

$medicines = Medicine::with(['weightage' => function($query) {
   $query->select(['id', 'name', 'medicine_id']);
}])->get(['id', 'name', 'description']);
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement