Laravel Collection is a class in the Laravel framework that provides a fluent and convenient way of working with arrays of data. It is essentially an object-oriented wrapper around PHP arrays that provides a number of useful methods for working with them.

Some of the key features of Laravel Collection are:

  1. Fluent syntax: Laravel Collection provides a fluent syntax for chaining together methods, allowing for clean and concise code.
  2. Higher-order messaging: Collections can be treated as first-class objects that can be passed around and manipulated with functions (called “higher-order messages”) that take other functions as arguments.
  3. Lazy loading: Many Collection methods return a new instance of the Collection, allowing for lazy loading of data, which can improve performance.
  4. Advanced filtering and mapping: Collections provide a variety of methods for filtering and mapping data, including methods for filtering by key, value, or callback, and mapping data to a new format.
  5. Support for pagination: Collections also provide support for pagination, allowing you to easily paginate large sets of data.

Use Case of Laravel Collection

There are numerous use cases for Laravel Collection in web development. Some of the most common use cases include:

  1. Querying and filtering database results: Laravel Collection provides an easy and convenient way to filter and query results retrieved from a database. It allows developers to write complex queries in a more readable and maintainable way.
  2. Manipulating and transforming data: Laravel Collection provides various methods for transforming and manipulating data. For example, it is possible to transform a collection of objects into an array, or to filter a collection of data based on specific criteria.
  3. Working with API responses: When working with API responses, it’s often necessary to manipulate and transform the data. Laravel Collection can be used to easily parse and filter data from API responses.
  4. Paginating large data sets: Collections provide support for pagination, which is useful when working with large data sets. Laravel Collection provides convenient methods for paginating data, making it easy to display data in small, manageable chunks.
  5. Working with arrays of data: Laravel Collection provides a fluent and convenient way of working with arrays of data, allowing developers to easily sort, filter, and manipulate data.

Create Laravel Collection

To create a new Laravel Collection, you can use the collect() helper function or the Illuminate\Support\Collection class.

Here’s an example using the collect() helper function:

$collection = collect([ ['name' => 'John', 'age' => 25],
['name' => 'Jane', 'age' => 30],
['name' => 'Bob', 'age' => 20],
]);

And here’s an example using the Illuminate\Support\Collection class:

use Illuminate\Support\Collection;
$collection = new Collection([ ['name' => 'John', 'age' => 25],
['name' => 'Jane', 'age' => 30],
['name' => 'Bob', 'age' => 20],
]);

In both cases, we pass an array of items to the collect() or Collection constructor. These items can be anything from simple integers or strings, to complex objects or arrays.

Once you have created a Laravel Collection, you can use the many methods available to manipulate and transform the data as needed.

Laravel Collections are “macroable”, meaning you can add your own custom methods to the Collection class at runtime. You can use the macro() method provided by the Illuminate\Support\Collection class to add new methods. This method accepts a closure that will be executed when the macro is called. Inside the closure, you can access the other methods of the Collection class using $this, just like a regular method.

Here’s an example that adds a custom toUpper() method to the Collection class:

use Illuminate\Support\Collection;
use Illuminate\Support\Str;

Collection::macro('toUpper', function () {
    return $this->map(function (string $value) {
        return Str::upper($value);
    });
});

$collection = collect(['first', 'second']);

$upper = $collection->toUpper();

// Output: ['FIRST', 'SECOND']

It’s generally recommended to declare collection macros in the boot() method of a service provider.

Laravel Collection Methods

Laravel collection to array

If you have a Laravel Collection and you want to convert it to a plain PHP array, you can use the toArray() method provided by the Illuminate\Support\Collection class.

Here’s an example:

use Illuminate\Support\Collection;

$collection = collect(['apple', 'banana', 'orange']);

$array = $collection->toArray();

// Output: ['apple', 'banana', 'orange']

In this example, we first create a Laravel Collection containing three elements. We then call the toArray() method on the Collection to convert it to a plain PHP array.

Note that if your Collection contains nested objects or arrays, the toArray() method will recursively convert them to arrays as well.

Laravel collection distinct

The distinct() method provided by the Illuminate\Support\Collection class can be used to remove duplicate values from a Collection.

Here’s an example:

use Illuminate\Support\Collection;

$collection = collect(['apple', 'banana', 'apple', 'orange', 'banana']);

$unique = $collection->distinct();

// Output: ['apple', 'banana', 'orange']

In this example, we first create a Laravel Collection containing five elements, with two of them being duplicates. We then call the distinct() method on the Collection to remove the duplicates and get a new Collection containing only the unique values.

Note that the distinct() method uses PHP’s === operator to compare values, so if your Collection contains objects, they will only be considered distinct if they are the exact same object instance. If you need to compare objects by value instead, you can use the unique() method with a custom callback function.

Laravel collection->push

The push() method provided by the Illuminate\Support\Collection class can be used to add one or more elements to the end of a Collection.

Here’s an example:

use Illuminate\Support\Collection;

$collection = collect(['apple', 'banana']);

$collection->push('orange');

// Output: ['apple', 'banana', 'orange']

$collection->push('grape', 'melon');

// Output: ['apple', 'banana', 'orange', 'grape', 'melon']

In this example, we first create a Laravel Collection containing two elements. We then call the push() method on the Collection to add a single element ('orange') to the end of the Collection. We can also pass multiple arguments to push() to add multiple elements to the end of the Collection.

Note that the push() method modifies the original Collection and returns the new number of elements in the Collection. If you want to add elements to the beginning of the Collection, you can use the prepend() method instead.

Laravel collection find

The find() method provided by the Illuminate\Support\Collection class can be used to search a Collection for the first element that satisfies a given condition.

Here’s an example:

use Illuminate\Support\Collection;

$collection = collect([
    ['id' => 1, 'name' => 'apple'],
    ['id' => 2, 'name' => 'banana'],
    ['id' => 3, 'name' => 'orange'],
]);

$item = $collection->find(function ($value, $key) {
    return $value['name'] === 'banana';
});

// Output: ['id' => 2, 'name' => 'banana']

In this example, we first create a Laravel Collection containing three associative arrays, each with an id and name field. We then call the find() method on the Collection and pass in a closure that returns true when the name field is 'banana'. The find() method returns the first element in the Collection for which the closure returns true.

Note that the find() method returns null if no element in the Collection satisfies the given condition. If you want to search for all elements that satisfy the condition, you can use the filter() method instead.

Laravel collection filter

The filter() method provided by the Illuminate\Support\Collection class can be used to filter a Collection based on a given condition.

Here’s an example:

use Illuminate\Support\Collection;

$collection = collect([
    ['id' => 1, 'name' => 'apple'],
    ['id' => 2, 'name' => 'banana'],
    ['id' => 3, 'name' => 'orange'],
]);

$filtered = $collection->filter(function ($value, $key) {
    return $value['name'] !== 'banana';
});

// Output: [
//     ['id' => 1, 'name' => 'apple'],
//     ['id' => 3, 'name' => 'orange'],
// ]

In this example, we first create a Laravel Collection containing three associative arrays, each with an id and name field. We then call the filter() method on the Collection and pass in a closure that returns true when the name field is not 'banana'. The filter() method returns a new Collection containing only the elements for which the closure returns true.

Note that the filter() method preserves the keys of the original Collection. If you want to reset the keys of the filtered Collection to consecutive integers, you can use the values() method after calling filter().

Laravel collection map

The map() method provided by the Illuminate\Support\Collection class can be used to transform a Collection by applying a function to each element.

Here’s an example:

use Illuminate\Support\Collection;

$collection = collect([1, 2, 3]);

$mapped = $collection->map(function ($value, $key) {
    return $value * 2;
});

// Output: [2, 4, 6]

In this example, we first create a Laravel Collection containing three integers. We then call the map() method on the Collection and pass in a closure that multiplies each element by 2. The map() method returns a new Collection containing the transformed elements.

Note that the map() method preserves the keys of the original Collection. If you want to reset the keys of the transformed Collection to consecutive integers, you can use the values() method after calling map().

Laravel collection merge

The merge() method provided by the Illuminate\Support\Collection class can be used to merge one or more arrays or Collections into a single Collection.

Here’s an example:

use Illuminate\Support\Collection;

$collection1 = collect(['apple', 'banana']);
$collection2 = collect(['orange', 'pear']);

$merged = $collection1->merge($collection2);

// Output: ['apple', 'banana', 'orange', 'pear']

In this example, we first create two Laravel Collections, each containing two strings. We then call the merge() method on the first Collection and pass in the second Collection as an argument. The merge() method returns a new Collection containing all the elements from both Collections.

Note that the merge() method preserves the keys of the original Collections. If you want to reset the keys of the merged Collection to consecutive integers, you can use the values() method after calling merge().

Laravel collection sort

The sort() method provided by the Illuminate\Support\Collection class can be used to sort a Collection by its values.

Here’s an example:

use Illuminate\Support\Collection;

$collection = collect([3, 2, 1]);

$sorted = $collection->sort();

// Output: [1, 2, 3]

In this example, we first create a Laravel Collection containing three integers. We then call the sort() method on the Collection, which returns a new Collection containing the same elements but sorted in ascending order.

By default, the sort() method sorts the Collection in ascending order. If you want to sort the Collection in descending order, you can use the sortByDesc() method instead.

You can also sort a Collection of associative arrays by specifying the key to sort on. For example:

use Illuminate\Support\Collection;

$collection = collect([
    ['name' => 'apple', 'price' => 2],
    ['name' => 'banana', 'price' => 1],
    ['name' => 'orange', 'price' => 3],
]);

$sorted = $collection->sortBy('price');

// Output: [
//     ['name' => 'banana', 'price' => 1],
//     ['name' => 'apple', 'price' => 2],
//     ['name' => 'orange', 'price' => 3],
// ]

In this example, we have a Laravel Collection containing three associative arrays, each with a name and price field. We call the sortBy() method on the Collection and pass in 'price' as the key to sort on. The sortBy() method returns a new Collection containing the same elements but sorted in ascending order by their price field.

Laravel collection foreach

The foreach loop is a common way to iterate over a Laravel Collection and perform some action on each of its elements.

Here’s an example:

use Illuminate\Support\Collection;

$collection = collect([1, 2, 3]);

$collection->each(function ($item, $key) {
    echo "{$key}: {$item}\n";
});

// Output:
// 0: 1
// 1: 2
// 2: 3

In this example, we first create a Laravel Collection containing three integers. We then call the each() method on the Collection and pass in a closure as an argument. The closure takes two parameters: the value of the current element ($item) and its key ($key). In this case, we simply print out the key and value of each element.

Note that the each() method does not modify the original Collection. If you want to modify the Collection as you iterate over it, you can use the transform() method instead.

You can also use a foreach loop to iterate over a Laravel Collection:

use Illuminate\Support\Collection;

$collection = collect([1, 2, 3]);

foreach ($collection as $item) {
    echo "{$item}\n";
}

// Output:
// 1
// 2
// 3

In this example, we use a foreach loop to iterate over the elements of the Collection and print each element on a new line. This is equivalent to calling the each() method with a closure that only takes one parameter.

Laravel collection each

The each() method is used to iterate over each element of a Laravel Collection and apply a callback function to it. The method takes a single argument, which is a closure that defines the action to perform on each element.

Here’s an example:

use Illuminate\Support\Collection;

$collection = collect([1, 2, 3]);

$collection->each(function ($item, $key) {
    echo "{$key}: {$item}\n";
});

// Output:
// 0: 1
// 1: 2
// 2: 3

In this example, we first create a Laravel Collection containing three integers. We then call the each() method on the Collection and pass in a closure as an argument. The closure takes two parameters: the value of the current element ($item) and its key ($key). In this case, we simply print out the key and value of each element.

Note that the each() method does not modify the original Collection. If you want to modify the Collection as you iterate over it, you can use the transform() method instead.

It’s worth noting that the each() method is similar to using a foreach loop, but it provides a more concise and functional approach to iterating over collections.

Laravel collection group by

The groupBy() method is used to group the elements of a Laravel Collection based on a given key or callback function. The method returns a new Collection where the elements are grouped according to the specified criteria.

Here’s an example:

use Illuminate\Support\Collection;

$collection = collect([
    ['name' => 'John', 'gender' => 'male'],
    ['name' => 'Jane', 'gender' => 'female'],
    ['name' => 'Bob', 'gender' => 'male'],
    ['name' => 'Mary', 'gender' => 'female'],
]);

$grouped = $collection->groupBy('gender');

$grouped->each(function ($group, $key) {
    echo "{$key}:\n";
    $group->each(function ($item) {
        echo "- {$item['name']}\n";
    });
});

// Output:
// male:
// - John
// - Bob
// female:
// - Jane
// - Mary

In this example, we first create a Laravel Collection of four elements, each of which is an associative array with a ‘name’ and ‘gender’ key. We then call the groupBy() method on the Collection and pass in the ‘gender’ key as the grouping criteria. The method returns a new Collection where the elements are grouped based on their ‘gender’ value.

We then use the each() method on the grouped Collection to iterate over each group and print out the key and name of each element in the group.

Note that the groupBy() method does not modify the original Collection. If you want to modify the Collection as you group its elements, you can use the groupBy() method in combination with the map() method.

Laravel collection where

The where() method is used to filter the elements of a Laravel Collection based on a given key-value pair or callback function. The method returns a new Collection containing only the elements that satisfy the specified condition.

Here’s an example:

use Illuminate\Support\Collection;

$collection = collect([
    ['name' => 'John', 'age' => 25],
    ['name' => 'Jane', 'age' => 30],
    ['name' => 'Bob', 'age' => 40],
    ['name' => 'Mary', 'age' => 35],
]);

$filtered = $collection->where('age', '>', 30);

$filtered->each(function ($item) {
    echo "{$item['name']} is over 30 years old.\n";
});

// Output:
// Jane is over 30 years old.
// Bob is over 30 years old.
// Mary is over 30 years old.

In this example, we first create a Laravel Collection of four elements, each of which is an associative array with a ‘name’ and ‘age’ key. We then call the where() method on the Collection and pass in the key-value pair ‘age’ > 30 as the filtering criteria. The method returns a new Collection containing only the elements with an ‘age’ value greater than 30.

We then use the each() method on the filtered Collection to iterate over each element and print out a message indicating that the person is over 30 years old.

Note that the where() method does not modify the original Collection. If you want to modify the Collection as you filter its elements, you can use the where() method in combination with the reject() or filter() method.

Laravel collection orderby

The orderBy() method is used to sort the elements of a Laravel Collection by one or more attributes. The method accepts one or more arguments, each of which is either a string representing the attribute to sort by or a closure that returns the value to sort by.

Here’s an example:

use Illuminate\Support\Collection;

$collection = collect([
    ['name' => 'John', 'age' => 25],
    ['name' => 'Jane', 'age' => 30],
    ['name' => 'Bob', 'age' => 40],
    ['name' => 'Mary', 'age' => 35],
]);

$sorted = $collection->orderBy('age');

$sorted->each(function ($item) {
    echo "{$item['name']} is {$item['age']} years old.\n";
});

// Output:
// John is 25 years old.
// Jane is 30 years old.
// Mary is 35 years old.
// Bob is 40 years old.

In this example, we first create a Laravel Collection of four elements, each of which is an associative array with a ‘name’ and ‘age’ key. We then call the orderBy() method on the Collection and pass in the ‘age’ string as the sorting criteria. The method returns a new Collection containing the same elements, but sorted in ascending order based on their ‘age’ value.

We then use the each() method on the sorted Collection to iterate over each element and print out a message indicating their name and age.

Note that the orderBy() method does not modify the original Collection. If you want to modify the Collection as you sort its elements, you can use the sortBy() or sortByDesc() method instead.

Laravel collection paginate

The paginate() method in Laravel Collection is used to split a large collection of items into smaller subsets that can be displayed on multiple pages. This method is similar to the paginate() method available for database queries in Laravel’s Eloquent ORM.

Here’s an example of using the paginate() method on a Collection:

use Illuminate\Support\Collection;

$collection = collect(range(1, 100));

$perPage = 10;

$currentPage = 1;

$paginated = $collection->forPage($currentPage, $perPage);

$paginated->each(function ($item) {
    echo $item . "\n";
});

In this example, we create a Collection of 100 elements using the collect() function and the range() function. We then define the number of items to display per page ($perPage) and the current page number ($currentPage). We use the forPage() method to extract a subset of the Collection that corresponds to the current page, passing in the page number and the number of items per page as arguments.

Finally, we use the each() method on the paginated Collection to iterate over each element and print it out.

Note that the paginate() method does not modify the original Collection. It returns a new Collection containing only the items for the current page. If you want to modify the original Collection as you paginate it, you can use the slice() method instead.

Laravel collection count

The count() method in Laravel Collection is used to count the number of items in the Collection. It returns an integer value representing the number of elements in the Collection.

Here’s an example of using the count() method on a Collection:

use Illuminate\Support\Collection;

$collection = collect([1, 2, 3, 4, 5]);

$count = $collection->count();

echo $count; // Output: 5

In this example, we create a Collection containing 5 elements using the collect() function. We then use the count() method to count the number of items in the Collection and store the result in a variable $count. Finally, we print out the value of $count using the echo statement.

Note that the count() method can also be used to count the number of items in a filtered Collection, as well as nested Collections. If you pass a closure to the count() method, it will return the number of elements that match the condition specified in the closure.

Laravel collection unique

The unique() method in Laravel Collection is used to remove duplicate values from a Collection. It returns a new Collection that contains only the unique values from the original Collection.

Here’s an example of using the unique() method on a Collection:

use Illuminate\Support\Collection;

$collection = collect([1, 2, 3, 2, 4, 3]);

$unique = $collection->unique();

$unique->each(function ($item) {
    echo $item . "\n";
});

In this example, we create a Collection containing 6 elements, including duplicates using the collect() function. We then use the unique() method to remove the duplicate values and store the result in a new Collection $unique. Finally, we use the each() method on the $unique Collection to iterate over each element and print it out.

Note that the unique() method does not modify the original Collection. It returns a new Collection containing only the unique values from the original Collection. The unique() method uses strict comparison (===) to determine if two values are the same. If you need to use a custom comparison function, you can pass a closure to the unique() method.

Laravel collection limit

The limit() method in Laravel Collection is used to limit the number of items returned by a Collection. It returns a new Collection containing the first n elements of the original Collection, where n is the number passed as an argument to the limit() method.

Here’s an example of using the limit() method on a Collection:

use Illuminate\Support\Collection;

$collection = collect([1, 2, 3, 4, 5]);

$limited = $collection->limit(3);

$limited->each(function ($item) {
    echo $item . "\n";
});

In this example, we create a Collection containing 5 elements using the collect() function. We then use the limit() method to limit the number of elements in the Collection to 3 and store the result in a new Collection $limited. Finally, we use the each() method on the $limited Collection to iterate over each element and print it out.

Note that the limit() method does not modify the original Collection. It returns a new Collection containing only the first n elements of the original Collection, where n is the number passed as an argument to the limit() method. If the original Collection contains fewer than n elements, the limit() method will return the entire Collection.

Laravel collection where like

The where() method in Laravel Collection can be used with the like operator to search for items in a Collection that match a given pattern. The where() method allows you to pass a closure that defines the condition that each element of the Collection must satisfy to be included in the result.

Here’s an example of using the where() method with the like operator:

use Illuminate\Support\Collection;

$collection = collect(['apple', 'banana', 'cherry', 'date', 'elderberry']);

$results = $collection->where('name', 'like', '%a%');

$results->each(function ($item) {
    echo $item . "\n";
});

In this example, we create a Collection containing 5 fruits using the collect() function. We then use the where() method to search for fruits that contain the letter ‘a’ in their name, using the like operator with the % wildcard. We store the result in a new Collection $results. Finally, we use the each() method on the $results Collection to iterate over each element and print it out.

Note that the where() method does not modify the original Collection. It returns a new Collection containing only the elements that satisfy the condition defined by the closure passed to it.

Laravel collection to JSON

Laravel Collection provides an easy way to convert a collection to a JSON string using the toJson() method. This method converts the collection to a JSON string representation of the collection’s items.

Here’s an example of using the toJson() method:

use Illuminate\Support\Collection;

$collection = collect([
    ['name' => 'John', 'age' => 25],
    ['name' => 'Jane', 'age' => 30],
    ['name' => 'Bob', 'age' => 45],
]);

$jsonString = $collection->toJson();

echo $jsonString;

In this example, we create a Collection containing 3 associative arrays. We then use the toJson() method to convert the Collection to a JSON string. Finally, we print the JSON string to the screen using the echo statement.

The output will be a JSON string:

[{"name":"John","age":25},{"name":"Jane","age":30},{"name":"Bob","age":45}]

Note that the toJson() method can also accept JSON options as an argument. These options are passed to the json_encode() function that is used internally to convert the collection to a JSON string. Here’s an example of using the toJson() method with options:

use Illuminate\Support\Collection;

$collection = collect([
    ['name' => 'John', 'age' => 25],
    ['name' => 'Jane', 'age' => 30],
    ['name' => 'Bob', 'age' => 45],
]);

$jsonString = $collection->toJson(JSON_PRETTY_PRINT);

echo $jsonString;

In this example, we use the JSON_PRETTY_PRINT option to format the JSON string with indentation and line breaks. The output will be:

[    {        "name": "John",        "age": 25    },    {        "name": "Jane",        "age": 30    },    {        "name": "Bob",        "age": 45    }]

Laravel collection to Object

Laravel Collection provides an easy way to convert a collection to an object using the toObject() method. This method converts the collection to an object representation of the collection’s items.

Here’s an example of using the toObject() method:

use Illuminate\Support\Collection;

$collection = collect([
    ['name' => 'John', 'age' => 25],
    ['name' => 'Jane', 'age' => 30],
    ['name' => 'Bob', 'age' => 45],
]);

$object = $collection->toObject();

var_dump($object);

In this example, we create a Collection containing 3 associative arrays. We then use the toObject() method to convert the Collection to an object. Finally, we print the object to the screen using the var_dump() function.

The output will be an object:

object(stdClass)#1 (3) {
  ["name"]=>
  string(4) "John"
  ["age"]=>
  int(25)
}
object(stdClass)#2 (3) {
  ["name"]=>
  string(4) "Jane"
  ["age"]=>
  int(30)
}
object(stdClass)#3 (3) {
  ["name"]=>
  string(3) "Bob"
  ["age"]=>
  int(45)
}

Note that the toObject() method converts each associative array in the collection to an object of the stdClass class. If the collection contains non-associative arrays or objects, they will be converted to objects of the stdClass class as well.

If you need to convert a collection to an object of a custom class, you can use the map() method to transform the collection items and then cast the collection to an object using (object) casting. Here’s an example:

use Illuminate\Support\Collection;

class Person
{
    public $name;
    public $age;

    public function __construct($name, $age)
    {
        $this->name = $name;
        $this->age = $age;
    }
}

$collection = collect([
    ['name' => 'John', 'age' => 25],
    ['name' => 'Jane', 'age' => 30],
    ['name' => 'Bob', 'age' => 45],
]);

$people = $collection->map(function ($item) {
    return new Person($item['name'], $item['age']);
});

$object = (object) $people;

var_dump($object);

In this example, we create a custom Person class with two properties: $name and $age. We then create a Collection containing 3 associative arrays. We use the map() method to transform each array to a Person object. Finally, we cast the collection to an object of the stdClass class using (object) casting. The output will be:

object(stdClass)#1 (3) {
  [0]=>
  object(App\Person)#2 (2) {
    ["name"]=>
    string(4) "John"
    ["age"]=>
    int(25)
  }
  [1]=>
  object(App\Person)#3 (2) {
    ["name"]=>
    string(4) "Jane"
    ["age"]=>
    int(30)
  }
  [2]=>
  object(App\Person)#4 (2) {
    ["name"]=>
    string(3) "Bob"
    ["age"]=>
    int(45)
  }
}

In conclusion, Laravel Collection provides a powerful set of methods for working with arrays of data in PHP. With its intuitive syntax and extensive functionality, it makes manipulating data much easier and efficient. Developers can use Collection’s various methods such as filter, map, merge, sort, group by, count, unique, limit, and many more to accomplish complex tasks in a few lines of code. Additionally, Laravel Collection allows developers to create custom methods and extend the class with their own logic using macros. Overall, the Laravel Collection is a must-have tool for developers working with arrays of data in PHP.

Categorized in: