Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you iterate over the properties of an eloquent object?

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

like image 701
Jimmyt1988 Avatar asked Oct 01 '14 14:10

Jimmyt1988


People also ask

How do you iterate over the properties of objects?

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.

What line of code is used to iterate through all the properties of an object?

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).

How do I iterate over an object in PHP?

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();


2 Answers

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

like image 169
Steve Avatar answered Oct 12 '22 18:10

Steve


You can also use getAttributes() method:

foreach ($project->getAttributes() as $k => $v) {
    echo $k.' '.$v."<br />";
}
like image 31
Marcin Nabiałek Avatar answered Oct 12 '22 18:10

Marcin Nabiałek