Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get ids array from related laravel model which is having belongsToMany relationship

I have a model Role which belongs to many Users.

Class Role {
     public $fillable = ["name"];

     public function users()
     {
          return $this->belongsToMany('App/Models/User')->select(['user_id']);
     }
}

When I retrieve users using with query in Role. I want It would return only user_ids array

 Role::with("users")->get();

it should return the following output

 [ 
   {
     "name": "Role1",
     "users" : [1,2,3]
   },
   {
     "name": "Role2",
     "users" : [1,2,3]
   }
 ]

Currently it gives following output

[ 
   {
     "name": "Role1",
     "users" : [
        {
           user_id : 1
        },
        {
           user_id : 2
        },

        {
           user_id : 3
        }
   },
   {
     "name": "Role2",
     "users" : [
        {
           user_id : 1
        },
        {
           user_id : 2
        },

        {
           user_id : 3
        }
     ]
   }
 ]
like image 406
sp11 Avatar asked Aug 19 '15 08:08

sp11


1 Answers

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()

like image 89
benJ Avatar answered Nov 18 '22 13:11

benJ