Laravel Collection Get First and Last Item Example
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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel Collection Implode Method Example
- Laravel Collection Has Method Example
- Laravel Collection Flip Method Example
- Laravel Collection Duplicates Method Example
- Laravel Collection diff(), diffAssoc() and diffKeys() Example
- Laravel Collection Concat Method Example
- Laravel Collection SortByDesc Tutorial with Examples
- Laravel Collection Merge | How to Merge Two Eloquent Collection?
- Laravel Collection Unique | Remove Duplicates from Collection Laravel
- Laravel Collection Search Method Example
- Laravel Collection Filter Method Example