Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i iterate over attributes in laravel models?

I have a Laravel model with many attributes. So, I need iterate over these attributes. How can I do this? Something like this:

@foreach($model->attributes as $attribute)
// use $attribute
@endforeach

is it possible?

like image 880
Wesin Alves Avatar asked Mar 06 '18 18:03

Wesin Alves


2 Answers

If you have an object, use getAttributes():

@foreach($model->getAttributes() as $key => $value)
    // use $attribute
@endforeach
like image 182
Alexey Mezenin Avatar answered Sep 20 '22 15:09

Alexey Mezenin


If these attributes were returned from a query, you can access the Model class directly:

E.g.

@foreach (User::all() as $user)
    <p>This is user {{ $user->id }}</p>
@endforeach

or, you can access the model reference given to a template:

E.g.

@foreach ($user->permissions as $permission)
    <p>This is an user permission {{ $permission->id }}</p>
@endforeach

See more in the Laravel Docs

like image 39
Abe Avatar answered Sep 19 '22 15:09

Abe