Get ids array from related laravel model which is having belongsToMany relationship
Personally, I wouldn't change the users()
relationship, but maybe add an accessor for user IDs
class Role { protected $fillable = ["name"]; // adding the appends value will call the accessor in the JSON response protected $appends = ['user_ids']; public function users() { return $this->belongsToMany('App/Models/User'); } public function getUserIdsAttribute() { return $this->users->pluck('user_id'); }}
Then you still have a working relationship, but can access the user IDs as an array in the Role response. If that doesn't work for you, as mentioned by @Creator, you could probably just add ->pluck('id')
in the relationship rather than the select()