Hi Dev,
Are you looking for example of laravel collection first element. if you want to see example of laravel collection firstwhere then you are a right place. let’s discuss about laravel collection firstwhere multiple. you'll learn laravel collection first example.
I will give you some examples of how to get first element from collection in laravel. you can easily add array in laravel 5, laravel 6 and laravel 7.
Let's see example:
Example 1: Laravel Collection First Example
public function index()
{
$collection = collect([
['id'=>1, 'name'=>'Hardik'],
['id'=>2, 'name'=>'Vimal'],
['id'=>3, 'name'=>'Harshad'],
['id'=>4, 'name'=>'Harsukh'],
]);
$first = $collection->first();
dd($first);
}
Output:
Array
(
[id] => 1
[name] => Hardik
)
Example 2: Laravel Collection First Where Example
public function index()
{
$collection = collect([
['id'=>1, 'name'=>'Hardik', 'salery' => '15000'],
['id'=>2, 'name'=>'Vimal', 'salery' => '10000'],
['id'=>3, 'name'=>'Harshad', 'salery' => '17000'],
['id'=>4, 'name'=>'Harsukh', 'salery' => '18000'],
]);
$first = $collection->firstWhere('name', 'Hardik');
dd($first);
}
Output:
Array
(
[id] => 1
[name] => Hardik
[salery] => 15000
)
Example 3: Laravel Collection First Where with Operator Example
public function index()
{
$collection = collect([
['id'=>1, 'name'=>'Hardik', 'salery' => 15000],
['id'=>2, 'name'=>'Vimal', 'salery' => 10000],
['id'=>3, 'name'=>'Harshad', 'salery' => 17000],
['id'=>4, 'name'=>'Harsukh', 'salery' => 18000],
]);
$first = $collection->firstWhere('salery', '>', 16000);
dd($first);
}
Output:
Array
(
[id] => 3
[name] => Harshad
[salery] => 17000
)
I hope it can help you...
Do you like below Tutorials ?
- PHP Laravel 5.5 - import export data into excel and csv using maatwebsite
- Laravel 7.x and 6.x create custom facade example from scratch
- Node JS - Get Real time online users counter using socket io example
- PHP Laravel 7.x and 6.x - Bootstrap Admin Theme Integration example from scratch
- MySQL Query - How to select records of today to next Sunday ?
- Laravel 7.x and 6.x - username custom validation example
- Laravel 5.5 - Import Extract zip file using chumper/zipper package
- PHP Laravel Set Custom Validation Error Messages Example