Laravel Collect Helper Methods Example

Laravel Collect Helper Methods Example

In this example i explain laravel collect helper method. We will discuss about laravel collection function. The Collection class allows you to chain its methods to perform fluent mapping and reducing of the underlying array.

Example 1 : Laravel Collect Helper

public function index()
{
    $collection = collect([1,2,3,4]);

   $collection->each(function($item){
      return $item*$item;
   });
}

Example 2 : Laravel Collection First Example

public function index()
{
    $collection = collect([
            ['id'=>1, 'name'=>'Sanket'],
            ['id'=>2, 'name'=>'Fenil'],
            ['id'=>3, 'name'=>'Ved'],
            ['id'=>4, 'name'=>'Shalok'],
        ]);
  
    $first = $collection->first();
  
    dd($first);
}

Example 3: Laravel Collection First Where Example

public function index()
{
    $collection = collect([
            ['id'=>1, 'name'=>'Sanket', 'salery' => '15000'],
            ['id'=>2, 'name'=>'Fenil', 'salery' => '10000'],
            ['id'=>3, 'name'=>'Ved', 'salery' => '17000'],
            ['id'=>4, 'name'=>'Shlok', 'salery' => '8000'],
        ]);
  
    $first = $collection->firstWhere('name', 'Sanket');
  
    dd($first);
}

I hope you understand of laravel collect and it can help you…