Laravel Collection Get First and Last Item Example

Oct 27, 2021 . Admin



Hi Guys,

Today, in this article I will explain to you how to get the first and the last item in laravel collection, I will show an example of how to get the last item from laravel collection.

Here, I will give you a full example of how to get the last item from laravel collection laravel collection get the first item, laravel collection get the last item as below so follow my all steps.

Get First Item:

Here, in this step we will get first item of collection.

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Support\Facades\Http;
  
class TestController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
                $collection = collect([
            [
                'id' => 1,
                'name' => 'Jack',
                'email' => 'jack@gmail.com'
            ],
            [
                'id' => 2,
                'name' => 'Will',
                'email' => 'will@gmail.com'
            ],
            [
                'id' => 3,
                'name' => 'Eric',
                'email' => 'eric@gmail.com'
            ],
            [
                'id' => 4,
                'name' => 'Wale',
                'email' => 'wale@gmail.com'
            ]
        ]);

        $firstRecord = $collection->first();

        dd($firstRecord);
    }
}
Output:
Array

(

    [id] => 1

    [name] => Jack

    [email] => jack@gmail.com

)
Get Last Item:

Here, in this step we will get last item of collection.

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Support\Facades\Http;
  
class TestController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
                $collection = collect([
            [
                'id' => 1,
                'name' => 'Jack',
                'email' => 'jack@gmail.com'
            ],
            [
                'id' => 2,
                'name' => 'Will',
                'email' => 'will@gmail.com'
            ],
            [
                'id' => 3,
                'name' => 'Eric',
                'email' => 'eric@gmail.com'
            ],
            [
                'id' => 4,
                'name' => 'Wale',
                'email' => 'wale@gmail.com'
            ]
        ]);

        $lastItem = $collection->last();

        dd($lastItem);
    }
}
Output:
Array

(

    [id] => 1

    [name] => Wale

    [email] => wale@gmail.com

)

It will help you...

#Laravel 8 #Laravel