How to transform an Eloquent Collection into a simple array?

1

I'm doing a query to the bank and a Collection is being returned ... How do I instead of having to call $role->role to get the column value, achieve 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);
    });
}
    
asked by anonymous 06.12.2018 / 19:30

1 answer

2

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

In your case, you would be: $roles = Role::all('role')->toArray();

But turning your collection into an array will not solve the problem as you expect, since the role you access ( $role->role ) is actually the column of your bank within your object. The solution would be to get only the value of the field you want:

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

More information:

  

link

     

link

    
06.12.2018 / 20:16