Laravel how to add to the collection
Laravel collections allow you to easily manipulate data. Learn how to add to a collection with an example.
Adding to a Collection in Laravel
Laravel provides an easy way to add a new item to a collection. The push()
method can be used to add a new item to the end of the collection. The syntax is as follows:
$collection->push($value);
The $value
can either be a single item, or an array of items. Here is an example of adding a single item to a collection:
$collection = collect([1, 2, 3]);
$collection->push(4);
// [1, 2, 3, 4]
Here is an example of adding multiple items to a collection:
$collection = collect([1, 2, 3]);
$collection->push([4, 5, 6]);
// [1, 2, 3, [4, 5, 6]]
It is also possible to add items to the beginning of the collection, using the prepend()
method. The syntax is as follows:
$collection->prepend($value);
The $value
can either be a single item, or an array of items. Here is an example of adding a single item to the beginning of a collection:
$collection = collect([1, 2, 3]);
$collection->prepend(0);
// [0, 1, 2, 3]
And here is an example of adding multiple items to the beginning of a collection:
$collection = collect([1, 2, 3]);
$collection->prepend([-2, -1]);
// [[-2, -1], 1, 2, 3]
In addition to the push()
and prepend()
methods, it is also possible to add items to a collection using the put()
method. The syntax is as follows:
$collection->put($key, $value);
The $key
is the key of the item in the collection, and the $value
is the value of the item. Here is an example of adding an item to a collection using the put()
method:
$collection = collect([
'name' => 'John',
'age' => 30
]);
$collection->put('gender', 'male');
// ['name' => 'John', 'age' => 30, 'gender' => 'male']
Finally, it is also possible to add items to a collection using the add()
method. The syntax is as follows:
$collection->add($value);
The $value
can either be a single item, or an array of items. Here is an example of adding an item to a collection using the add()
method:
$collection = collect([1, 2, 3]);
$collection->add(4);
// [1, 2, 3, 4]
In summary, Laravel provides several methods for adding items to a collection. The push()
method can be used to add items to the end of the collection, the prepend()
method can be used to add items to the beginning of the collection, the put()
method can be used to add items with a specific key, and the add()
method can be used to add a single item or an array of items.