Collections in Laravel

- Andrés Cruz

En español
Collections in Laravel

Este material forma parte de mi curso y libro completo; puedes adquirirlos desde el apartado de libros y/o cursos Curso y libro Laravel 11 con Tailwind Vue 3, introducción a Jetstream Livewire e Inerta desde cero - 2024.

Collections are nothing new, until now we have used collections in previous developments, every time we had a list as a response from the database to create a table in a view, collections are used:


And this is something very easy to see if you print the previous result in debug mode or tinker:

  #items: array:N

Collections in Laravel are an essential tool in Laravel to manage lists, but we can also create our own collections as we will see in this section.

Collections are nothing more than PHP arrays but with vitamins, this means that they are the same arrays but with a set of additional functionalities to make them easier and friendlier to use under the class:


Although, this class is not only used internally, we can also use it manually, that is, we can create a collection of an array in PHP:

$people = [
 ["name" => "user 1", "age" => 50],
 ["name" => "user 2", "age" => 70],
 ["name" => "user 3", "age" => 10],

To do this, we have several ways:

use Illuminate\Support\Facades\Collection;
$collection1 = collect($people);
$collection2 = new Collection($people);
$collection3 = Collection::make($people);
With the collection, it is now possible to use collection-specific methods of all types, such as the filter:
    return $value['age'] > 17;

Which returns a collection of those elements that meet the condition, in this example where the age is greater than 17:

Illuminate\Support\Collection {#5178
 all: [
   "name" => "user 1",
   "age" => 50,
   "name" => "user 2",
   "age" => 70,

By returning a collection from the filter() method, we can queue other operations on collections such as adding:

    return $value['age'] > 17;

Which in this case, does not return a collection, but an integer:


Another interesting method is the intercept method that removes any value from the original collection that is not present in the supplied array:

$collection = collect(['Desk', 'Sofa', 'Chair']);
$intersect = $collection->intersect(['Desk']);

And returns:

= Illuminate\Support\Collection {#5118
    all: [

These methods are specific to collections, you can review the official documentation to know the enormous number of methods that we only have available when using collections and that do not exist with arrays in:

Andrés Cruz

Desarrollo con Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz en Udemy

Acepto recibir anuncios de interes sobre este Blog.