1

this is becoming frustrating beyond imagination.

I need to get the column names from a table using Eloquent ORM in Laravel 5 combined with MongoDB. I have found some examples, but none of them is working for me as they are probably made for SQL specifically. I tried this and this without success, any idea?

Thanks!

The Condor
  • 1,034
  • 4
  • 16
  • 44

2 Answers2

2

It would be best to use the raw() method in this case and use the native MongoCollection methods like find() to iterate over the collection and get the keys in the documents array:

// Returns an array of field names from a collection of User models.
$keys = DB::collection('users')->raw(function($collection)
{
    $cursor = $collection->find();
    $array = iterator_to_array($cursor);
    $fields = array();
    foreach ($array as $k=>$v) {
        foreach ($v as $a=>$b) {
            $fields[] = $a;
        }
    }
    return array_values(array_unique($fields));    
});
chridam
  • 100,957
  • 23
  • 236
  • 235
0

MongoDB doesn't have columns or tables - the whole point is that it's schemaless therefore there are no columns for you to get the names of.

Because every document can be different, you'd need to get all documents in your collection and build an array of unique keys that each document contains.

See this answer: MongoDB Get names of all keys in collection

Community
  • 1
  • 1
ExoticChimp
  • 1,884
  • 1
  • 19
  • 37
  • Ok, so I need to extract the key names and save them in an array that I can pass to the view. The problem with the link you provided is that I can't do it inside Laravel/Eloquent (as far as I know, noob here). Any suggestion? – The Condor Sep 21 '15 at 08:34