Laravel: how can I loop through the fields and relations of an ORM

jaget picture jaget · Nov 12, 2012 · Viewed 8k times · Source

In Laravel if I create an ORM for a table, lets say pages

Is there a way to list/loop through all the tables fields and their values (from the database), and on top of that is there a way to list/loop through all the relationships.

Is there a way to access the attributes/fields of an orm object such as:

foreach($pages->fields_array as $f){
    //do something with field
}

What I'm trying to do is get a dynamic list of fields and their values so I can auto build a form.

As for the relations I am trying to loop through all related tables to create a dropdown list of linked tables.

Answer

keithics picture keithics · Aug 9, 2013

in Laravel 3 you can loop with $page->attributes

But not in Laravel 4.

Just do this instead and do for each after.

$page->toArray(); // it will convert the model object into an array :)

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