Laravel Collection Get First and Last Item Example

By Hardik Savani April 16, 2024 Category : Laravel

This post will give you example of laravel collection get last and first item. if you have question about how to get last item from laravel collection then i will give simple example with solution. this example will help you how to get first item from laravel collection. We will use laravel collection get first item.

we can get first and last item from collection in laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 application.

Here, i will give you very simple example of getting last item from laravel collection and getting first item from laravel collection. let's see both example here:

I have one created items table that structure as bellow you can see.

Get First Item:

Controller Code:

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Http;

class ITSController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index()

{

$collection = collect([

[

'id' => 1,

'name' => 'One',

'email' => 'one@gmail.com'

],

[

'id' => 2,

'name' => 'Two',

'email' => 'two@gmail.com'

],

[

'id' => 3,

'name' => 'Three',

'email' => 'three@gmail.com'

],

[

'id' => 4,

'name' => 'Four',

'email' => 'four@gmail.com'

]

]);

$first = $collection->first();

dd($first);

}

}

Output:

Array

(

[id] => 1

[name] => One

[email] => one@gmail.com

)

Get Last Item:

Controller Code:

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Http;

class ITSController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index()

{

$collection = collect([

[

'id' => 1,

'name' => 'One',

'email' => 'one@gmail.com'

],

[

'id' => 2,

'name' => 'Two',

'email' => 'two@gmail.com'

],

[

'id' => 3,

'name' => 'Three',

'email' => 'three@gmail.com'

],

[

'id' => 4,

'name' => 'Four',

'email' => 'four@gmail.com'

]

]);

$last = $collection->last();

dd($last);

}

}

Output:

Array

(

[id] => 4

[name] => Four

[email] => four@gmail.com

)

I hope it can help you...

Tags :
Shares