Video Tutorial Laravel Collections


Collections are a type of class that can represent a series of data and make it possible to bring a more object-oriented solution to the processing of tables.

Why not use the tables?

Before wanting to add a new concept in our application it is important to understand the problems posed by the use of tables.

The composition of the functions

The readability of functions is not obvious when they are chained.

array_values ​​(
    array_map (function ($ student) {
        return $ pupil ('name');
    }, array_filter ($ students, function ($ student) {
        return $ student ('note')> = 10;
    }))
)

Some functions like uasort () can not be used directly because they expect parameters passed by reference (which forces the creation of intermediate variables).

The lack of consistency of functions

This is more to prove but the order of the parameters is not uniform.

uasort (array & $ array, callable $ value_compare_func): bool
array_filter (array $ array (, callable $ callback (, int $ flag = 0))): array
array_map (callable $ callback, array $ array1 (, array $ ...)): array

Mutation or not?

Finally, some functions alters the original array (array_splice and array_shift for example) while other no, which can be misleading in some situations.

The collections

The collections make it possible to correct these different problems:

  • Most of the methods return a new collection which simplifies the composition and
  • The order of the arguments can be unified
collect ($ pupils)
  -> filter (function ($ high) {
    return $ student ('note')> = 10;
  })
  -> map (function ($ high) {
    return $ student ('name')
  })
  -> values ​​()
  -> toArray ();

Even if it is possible to develop your own collection system it may be interesting to rely on an existing library to save time (especially if you want a well tested code).

tightenco / collect

Laravel has a rather complete Collection System but does not offer a separate framework package. But one person was motivated to separate the collections into a dedicated package.

This class offers a hundred methods and has an original system of Higher Order Messages.

collect ($ pupils)
  -> map (function ($ high) {
    return $ student ('name')
  })
  -> values ​​()
  -> toArray ();

// can be shortened
collect ($ pupils)
  -> map-> name
  -> values ​​()
  -> toArray ();