Andreas Hunter
Andreas Hunter

Reputation: 5004

Laravel eager loading specific columns error

I have custom code where I must get specific columns from relation data:

$jobs = Job::with('user:id, name')
           ->where('type', 0)
           ->where('status', 1)
           ->orderBy('updated_at', 'DESC')
           ->get();

When I run this code Laravel return me error message:

SQLSTATE[42S22]: Column not found: 1054 Unknown column ' name' in 'field list'

How can I solve this error?

Upvotes: 1

Views: 413

Answers (2)

Brinda Fadadu
Brinda Fadadu

Reputation: 144

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

$jobs = Job::with(['user' =>  function($q){
                $q->select('id','name');
            }])->where('type', 0)
               ->where('status', 1)
               ->orderBy('updated_at', 'DESC')
               ->get();

Upvotes: 4

Davit Zeynalyan
Davit Zeynalyan

Reputation: 8618

In this code has space with('user:id, name'). Problem is space.
Try this one

$jobs = Job::with('user:id,name')
    ->where('type', 0)
    ->where('status', 1)
    ->orderBy('updated_at', 'DESC')
    ->get();

Upvotes: 4

Related Questions