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

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

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Extracting Plain ID Arrays from belongsToMany Relationships in Laravel

When working with many-to-many relationships in Laravel, it is common to need a flattened list of identifiers rather than full model instances. Consider a scenario where you have a Role model that relates to many User models. You define the relationship like this:

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

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

You then eager load this relationship and expect the users attribute to be a simple array of IDs:

$roles = Role::with("users")->get();

However, Laravel's JSON serialization defaults to including all selected columns as objects. Even though you have limited the selection to user_id, the resulting JSON looks like this:

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

What you actually want is a flat array of integers:

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

The root cause lies in how Laravel handles the collection returned by a relationship. When you eager load with with("users"), Laravel returns a collection of model instances (or objects representing the selected columns) for each relationship. Simply adding ->select(['user_id']) changes the shape of the underlying data but does not change the fact that Laravel is still treating it as a collection of items, which serialize to objects in JSON.

To get a plain array of IDs, you need to transform the relationship's return value into an array using the pluck() method or by accessing the underlying key directly. The most direct approach is to override how the relationship behaves when accessed via eager loading. You can do this by defining a custom accessor on the model or by transforming the data after retrieval.

One clean solution is to use the getRelationValue() method inside your controller or serializer, but that requires manual transformation in every place you consume the data. A more elegant pattern is to define an accessor that automatically converts the relationship into an ID array when accessed:

class Role {
    public function getUsersAttribute($value)
    {
        return $value instanceof \Illuminate\Support\Collection
            ? $value->pluck('user_id')->toArray()
            : [];
    }
}

However, this only works if the relationship is actually queried. If you want to force the transformation at the relationship definition level without altering every access point, consider using a custom accessor on the users relationship itself by leveraging get() and transforming it within the relationship method:

public function users()
{
    return $this->belongsToMany('App\Models\User')
        ->select(['user_id'])
        ->get(); // Force eager loading of just IDs as a collection
}

This approach ensures that when Laravel resolves the users attribute, it returns a collection where each item is an object containing only user_id. When you later access $role->users, you still get a collection, but now you can easily transform it to an ID array in your serializer or controller:

$roles = Role::with("users")->get();

foreach ($roles as $role) {
    $role->users = $role->users->pluck('user_id')->toArray();
}

If you are using a JSON API resource, you can apply the transformation inside your resource class using transform() or by overriding the relationship accessor. This keeps your models clean and moves the presentation logic to the layer responsible for serialization.

Another option is to use ->get()->pluck('user_id')->toArray() directly in the relationship method if you are certain the relationship will always be eager loaded. However, this breaks the contract of returning a relationship collection and may cause issues if other parts of your code expect a collection.

The trade-off here is between model purity and convenience. Returning an array of IDs from a belongsToMany relationship simplifies downstream processing but removes the ability to access other columns via $role->users[0]->name. If you need those details later, keep the full models and transform only when sending JSON responses.

For most API endpoints, transforming the relationship in your resource class or controller is the safest and most maintainable approach. It avoids coupling your model's internal structure to specific serialization needs while keeping your codebase predictable and easy to refactor.

Our network