Home Ask Login Register

Developers Planet

Your answer is one click away!

Lovelock February 2016

Laravel 5 - return only one field from relationship

have a relationship which returns rows from a pivot table.

However I just want to return a collection of the user ids from the table.

If I have it as current:

public function followers()
    return $this->hasMany('App\Follower')->select(array('project_id', 'user_id'));

It will return the 2 fields, but if I just have the select with a single field:

public function followers()
    return $this->hasMany('App\Follower')->select( 'user_id');

It returns an an empty object.

Any ideas?


patricus February 2016

I'm guessing this function is in your Project model. When modifying the select on a relationship, you must, at a minimum, select the fields needed to match the records together.

In this case, if this in on your Project model, if you don't select the project_id from the related table, Laravel can't match up the Follower objects with the correct Project objects, since Laravel won't have any idea which Project the Follower belongs to without the foreign key.

Post Status

Asked in February 2016
Viewed 3,497 times
Voted 6
Answered 1 times


Leave an answer

Quote of the day: live life