ItSolutionStuff.com

Laravel Collection Check If Key Exists Example

By Hardik Savani • April 16, 2024
Laravel

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...

Tags: Laravel
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

How to Select Specific Columns in Laravel Eloquent Model?

Read Now →

How to Get Columns Names from Model in Laravel?

Read Now →

Laravel Collection Get Unique Values Example

Read Now →

Laravel Collection Get First and Last Item Example

Read Now →

Laravel Collection keys() Method Example

Read Now →

Laravel Collection intersect() and intersectByKeys() Method Example

Read Now →

Laravel Collection SortBy Tutorial with Examples

Read Now →

Laravel Collection Merge | How to Merge Two Eloquent Collection?

Read Now →

Laravel Collection Unique | Remove Duplicates from Collection Laravel

Read Now →

Laravel Collection Search Method Example

Read Now →

Laravel Collection Filter Method Example

Read Now →

Merge Multiple Collection Paginate in Laravel

Read Now →