The above almost gives me what I need. But I'm also getting the pivot table.
And in the end, I would like to get the ids as an array, and not id: 1, id: 2 etc.
How do I do this?
$model->belongsToManyRelation()->getRelatedIds();
// or if you want to ensure unique ids:
$model->belongsToManyRelation()->distinct()->getRelatedIds();
public function role_ids()
{
return $this->belongsToMany('App\Role')->getRelatedIds();
return $this->belongsToMany('App\Role')->distinct()->getRelatedIds();
return $this->roles()->getRelatedIds();
return $this->roles()->distinct()->getRelatedIds();
}
All of the above ways to do it ends with:
Fatal error: Call to a member function addEagerConstraints() on array in /home/vagrant/Code/Acme/api/vendor/illuminate/database/Eloquent/Builder.php on line 424
@henninghorn You're doing it wrong. Relation method must return Relation object, not an array.
public function roles()
{
return $this->belongsToMany('App\Role');
}
// then either:
$user->roles()->getRelatedIds();
// or add a method for this:
public function getRoleIds()
{
return $this->roles()->getRelatedIds();
}
$user->getRoleIds();
And if you want to use $user->roleIds as property, then use accessor.
I chose to solve the problem using Fractal, which means I added a presenter that strips out the unnecessary data from the pivot table and it also puts the ids in an array.
@henninghorn Yeah, presenter is the way to prepare your response.
However, I don't know the package, so I won't suggest anything about fetching this data.
From the eloquent point of view, you could simply create an accessor that gets role ids as an array and append it to the array/json representation of your model.
Yeah, that could be an option too.
The only problems is, that I don't want to return/display role ids everytime I request the user data.
I'm building an API, and only when an admin wants to edit a user the role ids should be included.