Can you iterate over the properties of an eloquent object?

Jimmyt1988 picture Jimmyt1988 · Oct 1, 2014 · Viewed 7.3k times · Source

If I have for example:

$project = new Project(); // Project is a class that extends Eloquent
$project->title;
$project->something;

Is it possible to iterate over those properties... something like this:

foreach( $project as $key => $value )
{
    echo $key;
}

I am trying to do this to achieve a unit of work for editing Eloquent models

Answer

Steve picture Steve · Oct 1, 2014

You can use the toArray() method:

foreach( $project->toArray() as $key => $value )
{
    echo $key;
}

http://laravel.com/docs/4.2/eloquent#converting-to-arrays-or-json