How to turn an Eloquent Collection into a simple array?

Asked

Viewed 329 times

1

I am making a consultation to the bank and is being returned a Collection... How do I stop instead of having to call $role->role to get the column value, get the same behavior by calling only $role?

Current code:

$roles = Role::all('role');

foreach ($roles as $role) {
    Gate::define($role->role, function ($user) use ($role) {
        return $user->roles->contains('role', $role->role);
    });
}
  • Try Role::all('role')->toArray();

  • I didn’t understand your doubt?

1 answer

2


You can serialize Models and Collections via the command toArray()

In your case I’d be: $roles = Role::all('role')->toArray();

But turning your Collection into array will not solve the problem as you expect, as the scroll you access ($role->role) in fact it is the column of your bank, within your object. The solution would get only the value of the field you want:

$roles = Role::pluck('role')->all()

More information:

https://laravel.com/docs/5.7/eloquent-serialization

https://laravel.com/docs/5.7/collections#method-Pluck

Browser other questions tagged

You are not signed in. Login or sign up in order to post.