Laravel Collection Check If Key Exists Example

By Hardik Savani April 16, 2024 Category : 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 :
Shares