3

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.

afarazit
  • 4,907
  • 2
  • 27
  • 51
jaget
  • 2,149
  • 6
  • 21
  • 29

2 Answers2

4

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

keithics
  • 8,576
  • 2
  • 48
  • 35
1

Here's how i loop through an object and it's relations (images is the relation for this example)

$page = Page::with('images')->first();

// Laravel 4
foreach($page->attributes as $attr)
{
     dd($attr);
}

// Laravel 5
foreach($page->getAttributes() as $attr)
{
     dd($attr);
}
afarazit
  • 4,907
  • 2
  • 27
  • 51
  • What I mean is under the ORM object is there an array attribute of something like fields? So that I can go foreach($pages->attributes as $a){do something} – jaget Nov 12 '12 at 13:14
  • I just stumbled across this answer and this does not work in laravel 5.8. Instead we can use $page->getAttributes() to achieve the same. – Suraj Jun 11 '19 at 05:03