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
Method 1: Using for…in loop: The properties of the object can be iterated over using a for..in loop. This loop is used to iterate over all non-Symbol iterable properties of an object. Some objects may contain properties that may be inherited from their prototypes.
Description. The loop will iterate over all enumerable properties of the object itself and those the object inherits from its prototype chain (properties of nearer prototypes take precedence over those of prototypes further away from the object in its prototype chain).
PHP provides a way for objects to be defined so it is possible to iterate through a list of items, with, for example a foreach statement. By default, all visible properties will be used for the iteration. echo "\n"; $class->iterateVisible();
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
You can also use getAttributes()
method:
foreach ($project->getAttributes() as $k => $v) {
echo $k.' '.$v."<br />";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With