Laravel Collection Check If Key Exists Example
Hello Guys,
This article is focused on laravel collection check if key exists. Here you will learn how to check key exists in collection of laravel. This example will help you check if key exists in collection laravel. you can see laravel collection has key check. Follow the below tutorial step of laravel check if collection has key.
You can use this example with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 version.
If you need to check if key is exists on laravel collection object then laravel provides has() method to check it. you can check whether it is with a single key and whether multiple keys exist or not as well. so let's see a simple example with output:
Example 1:
PostController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PostController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index(Request $request)
{
$post = collect([
'id' => 1,
'name' => 'Hardik Savani',
'email' => 'hardik@gmail.com'
]);
if ($post->has('name')) {
dd("Name key is exist on collection.");
}
dd("Name key is not exist on collection.");
}
}
Output:
Name key is exist on collection.
Example 2:
PostController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PostController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index(Request $request)
{
$post = collect([
'id' => 1,
'name' => 'Hardik Savani',
'email' => 'hardik@gmail.com'
]);
if ($post->has(['name', 'email'])) {
dd("Name and Email key is exist on collection.");
}
dd("Name and Email key is not exist on collection.");
}
}
Output:
Name and Email key is exist on collection.
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
- How to Select Specific Columns in Laravel Eloquent Model?
- How to Get Columns Names from Model in Laravel?
- Laravel Collection Get Unique Values Example
- Laravel Collection Get First and Last Item Example
- Laravel Collection keys() Method Example
- Laravel Collection intersect() and intersectByKeys() Method Example
- Laravel Collection SortBy 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
- Merge Multiple Collection Paginate in Laravel