Home Laravel Laravel Collection Check If Key Exists

Laravel Collection Check If Key Exists

by Shahriar Sagor

Today now in this article is i will focused on the laravel collection check if any key exists. So here you will learn about how to check key exists in collection of laravel. So in this example i will help you how check if key exists in collection laravel. Then here you can see the laravel collection has key check. Just follow the below tutorial step by step of laravel check if collection has key.

We can also use this example with laravel 6, laravel 7, laravel 8 and laravel 9 any version.

If you want to check if key is exists on laravel collection on object then laravel is provides has() method to check it. We can also check whether it is with a single key and also whether multiple keys exist or not as well. so let’s start and 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.");
    }
}

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.");
    }
}

Read Also: php artisan serve not working in Laravel

Thanks for read. I hope it help you. For more you can follow us on facebook

close

You may also like