Today's Lesson: Using Collections in Laravel

·

1 min read

What is a collection in Laravel?

The collection is a feature in the Laravel core that aims to make it easier for us to manage arrays. Now consider using collections if you've been using native PHP features to manage arrays because the collection has many helper features that are very helpful.

image.png

For information, the model class also returns the results in the form of a collection. This means that if you convert an array to a collection you can also use queries as you did in the model.

image.png

How to use Collections.

You can do this in two ways:

  1. Simple way to use helper collect.

    $collection = collect([1, 2, 3]);
    
  2. The second way is to use the collection class.

    use Illuminate\Support\Collection;
    
    $collection = new Collection(['PHP', 'Laravel', 'HTML', 'Bootstrap']);
    

Case studies using Collections.

I recently took advantage of the collection feature in my project.

Case 1: I want to get the total price from the user input.

<input name="price[]">
<input name="price[]">
$total = collect(request('price'))->sum();

Case 2: I want to check whether the data entered by the user is in the database.

$stockFromDB = Product::all()->pluck('id');

if ($stockFromDB->contains($stockFromUser)) {

}