Laravel Collection | Part 3
Welcome back to our journey through the enchanting world of Laravel Collections! In Part 1 and Part 2, we uncovered some remarkable methods that allowed us to dance with data effortlessly. Now, in Part 3, we'll continue our exploration with a fresh set of unique collection methods that will make your data-handling tasks a breeze.
31. filter()
The filter
method is your trusty companion when it comes to selectively filtering elements from a collection based on a callback function.
$collection = collect([1, 2, 3, 4, 5]);
$filtered = $collection->filter(fn ($item) => $item % 2 === 0);
// Result: [2, 4]
32. first()
The first
method returns the first item from the collection that meets the specified criteria or the first item in the collection if no criteria are given.
$collection = collect([1, 2, 3, 4, 5]);
$collection->first();
// Result: 1
$firstEven = $collection->first(fn ($item) => $item % 2 === 0);
// Result: 2
33. firstOrFail()
Similar to first
, the firstOrFail
method returns the first item that meets the criteria. However, if no item is found, it throws an exception (Illuminate\Support\ItemNotFoundException
).
$collection = collect([1, 3, 5]);
$collection->firstOrFail();
// Result: 1
$firstEven = $collection->firstOrFail(fn ($item) => $item % 2 === 0);
// Throws an exception: Illuminate\Support\ItemNotFoundException
34. firstWhere()
The firstWhere
method returns the first item with the specified key-value pair.
$collection = collect([
['name' => 'Alice', 'age' => 30],
['name' => 'Bob', 'age' => 25],
['name' => 'Charlie', 'age' => 35],
]);
$firstCharlie = $collection->firstWhere('name', 'Charlie');
// Result: ['name' => 'Charlie', 'age' => 35]
You can also pass the comparison operator as a second parameter and the tester as the third parameter:
$collection->firstWhere('age', '<', 30);
// Result: ['name' => 'Bob', 'age' => 25]
35. flatMap()
The flatMap
method applies a callback to each item in the collection and flattens the results into a single collection. You can perform any operation on the array item inside the callback.
$collection = collect([
['name' => 'Alice'],
['age' => 30],
]);
$transformed = $collection->flatMap(fn ($item) $item);
// Result: ['name' => 'Alice', 'age' => 30]
36. flatten()
This method is straight forward, it converts a multi-dimensional collection into a single-dimensional one.
$collection = collect([1, [2, 3], [4, 5], [[[ 6 ], 7], 8] ]);
$flattened = $collection->flatten();
// Result: [1, 2, 3, 4, 5, 6, 7, 8]
This method takes a depth
parameter that specify up to what depth the array may be flattened:
$flattened = $collection->flatten(1); // Result: [1, 2, 3, 4, 5, [[ 6,], 7, ], 8,]
37. flip()
The flip
method swaps the keys and values of a collection.
$collection = collect(['a' => 1, 'b' => 2, 'c' => 3]);
$flipped = $collection->flip();
// Result: [1 => 'a', 2 => 'b', 3 => 'c']
38. forget()
The forget
method removes an item from the collection by its key. It will modify the collection and will not return the resultant array
$collection = collect(['a' => 1, 'b' => 2, 'c' => 3]);
$collection->forget('b');
// Result: ['a' => 1, 'c' => 3]
39. forPage()
The forPage
method returns a new collection containing items from a specific page when paginating. The first parameter is the page number, and the second parameter is the number of items to be returned.
$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]);
$page2 = $collection->forPage(1, 4);
// Result: [1, 2, 3, 4]
40. get()
The get
method retrieves an item from the collection by its key. You can also provide a default value if the key is not found, you can also pass a callback in place of default value.
$collection = collect(['a' => 1, 'b' => 2, 'c' => 3]);
$value = $collection->get('b');
// Result: 2
$value = $collection->get('d', 33);
// Result: 33
$value = $collection->get('e', fn() => User::find(11)->age);
// Result: 32
41. groupBy()
The groupBy
method groups the items in the collection by a specified key or a callback function. Multiple grouping is also possible by passing an array.
$collection = collect([
['name' => 'Alice', 'age' => 30],
['name' => 'Bob', 'age' => 25],
['name' => 'Charlie', 'age' => 30],
]);
$grouped = $collection->groupBy('age');
// Result: [
// 30 => [
// ['name' => 'Alice', 'age' => 30],
// ['name' => 'Charlie', 'age' => 30],
// ],
// 25 => [
// ['name' => 'Bob', 'age' => 25],
// ],
// ]
$grouped = $collection->groupBy(fn($item) => $item['age'] > 25);
// Result: [
// 1 => [
// [
// "name" => "Alice",
// "age" => 30,
// ],
// [
// "name" => "Charlie",
// "age" => 30,
// ],
// ],
// 0 => [
// [
// "name" => "Bob",
// "age" => 25,
// ],
// ],
// ],
42. has()
The has
method tests if the collection contains a specific key.
$collection = collect(['a' => 1, 'b' => 2, 'c' => 3]);
$hasKey = $collection->has('b');
// Result: true
43. hasAny()
The hasAny
method checks if the collection contains any of the specified keys array.
$collection = collect(['a' => 1, 'b' => 2, 'c' => 3]);
$hasAnyKeys = $collection->hasAny(['b', 'd']);
// Result: true
44. implode()
The implode
method joins the items in the collection into a string using a specified delimiter. You can also operate over a multi-dimensional array and the first parameter can also be a callback function.
$collection = collect(['apple', 'banana', 'cherry']);
$fruits = $collection->implode(', ');
// Result: 'apple, banana, cherry'
// Multi-dimensional array
$collection = collect([['name' => 'apple'], ['name' => 'banana'], ['name' => 'cherry']]);
$fruits = $collection->implode('name',', ');
// Result: "apple, banana, cherry"
// Callback example
$collection = collect([['age' => 20], ['age' => 22], ['age' => 35]]);
$evenAges = $collection->implode(fn($item) => $item['age'] % 2 === 0 ? $item['age'] : '', ', ');
// Result: "20, 22, "
45. intersect()
The intersect
method returns a new collection containing the items that are present in both the original collection and another collection.
$collection1 = collect([1, 2, 3]);
$collection2 = collect([2, 3, 4]);
$intersection = $collection1->intersect($collection2);
// Result: [2, 3]
You've now added a whole new set of tools to your Laravel Collections arsenal. These methods will empower you to manipulate and transform data with ease and finesse. Stay tuned for the next installment of our journey into Laravel Collections, where we'll continue to uncover the magic they hold. Happy coding!