0

What are the advantages of Laravel ORM?

I would like to ask if the Collection returned from the Model will be used directly?

Or will it be converted into Array for use?

Because the efficiency of foreach Collection is not comparable to the efficiency of Array

Is there really an advantage to using ORM's relation?

2 Answers2

0

Part of your question is asking for opinions, which isn't really what Stack Overflow is for, but to answer the part which isn't, a Collection can be returned as a pure PHP array using the ->toArray() method on it.

Whether you elect to do so or not is a subjective choice.

Giles Bennett
  • 1,509
  • 1
  • 12
  • 15
0

The efficiency of a Collection versus an array is convenience. It's easy to modify the collection, to filter it, map it and perform other tasks with it.

Of course this can be done with native PHP methods as well like array_map and array_walk, but you'll have to remember the methods yourself.

But Laravel collections bring so much more utility features that would take a lot of boilerplate code in native PHP, which is harder to read and process in a glance. In a collection query it is much cleaner and easier to read it as self documenting code.

something like

   $black_puppies_collection = $dogs_collection
      ->where('color', 'black')
      ->where('age', '<','1')
      ->mapToGroups(function($dog, $index) {
           return [$dog['race'] => $dog]];
       });
   $border_collie_puppies = $black_puppies_collection['border_collies'];

In native php this would become something like:

$black_puppies = array_filter(function($dog) {
    return $dog['color'] == 'black' && $dog['age'] < 1;
});
$black_puppies = array_reduce(function($accumulator, $dog) {
   $accumulator[$dog['race']] = $dog;
   return $accumulator;
});
$border_collie_puppies = $black_puppies['border_collies'];

All in all not a big difference, but the coding ease with daisy chaining methods, and just make it into a simple instruction set with autocompleting IDE's makes it a breeze to work with large and small sets of data.

Collections save coding time and effort, that would be the major reason to shift to them. And rarely the effort is needed to go native for speed in php.

You will most likely use the collection directly to loop over of in a foreach for whatever purpose you need it.

foreach($collection as $model) {
   $this->doMagic($model);
}

The advantage of ORM relations is hard to explain, but when you get comfortable with them and the collections, you wish every other framework would have them.

Personally I'm more a fan of WinterCMS's implementations of relations and models in their storm library, as they improve upon the Laravel method of making relations, cutting down a lot of the boilerplate code you need to do with Laravel.

Tschallacka
  • 27,901
  • 14
  • 88
  • 133