Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

yonka's avatar

How to Solve this error "count(): Argument #1 ($value) must be of type Countable|array, null given"

I want get the inventory if exist, if not I want create new one but I am receiveing an error

$inventory = Inventory::where('inventory_item_id',$itemData['id'])->first();

I want check if inventory is empty or not

0 likes
2 replies
LaryAI's avatar

Solution:

The error message:

count(): Argument #1 ($value) must be of type Countable|array, null given

means you are trying to use the count() function on a variable that is null. In your code:

$inventory = Inventory::where('inventory_item_id', $itemData['id'])->first();

The first() method returns either an instance of Inventory or null if no record is found.

If you want to check if an inventory exists, you should check if $inventory is null (not use count()):

$inventory = Inventory::where('inventory_item_id', $itemData['id'])->first();

if ($inventory) {
    // Inventory exists
} else {
    // Inventory does not exist, create a new one
    $inventory = Inventory::create([
        'inventory_item_id' => $itemData['id'],
        // add other fields as needed
    ]);
}

Summary:

  • Do not use count() on the result of first().
  • Use a simple if ($inventory) check to see if a record was found.
Snapey's avatar

if you want to know if it exists then use ->exists()

if (Inventory::where('inventory_item_id',$itemData['id'])->exists())

		// it exists

}

if you want to get the inventory (for other reasons), just check if it is null

$inventory = Inventory::where('inventory_item_id',$itemData['id'])->first();

if($inventory) {

    // it exists

}
1 like

Please or to participate in this conversation.