In Laravel 11.x & Laravel 12.x, the Arr::hasAny() method is a convenient way to check if any of the specified keys exist in a given array. This method is part of Laravel Illuminate\Support\Arr helper class, which provides useful array manipulation utilities.
Syntax
Arr::hasAny(array $array, array|string $keys): bool$array: The array to check. $keys: A single key (string) or an array of keys to check for existence in the array. Returns: true if any of the keys exist in the array, otherwise false.
<?php use Illuminate\Support\Arr; $array = ['product' => ['name' => 'Desk', 'price' => 100]]; $contains = Arr::hasAny($array, 'product.name'); // true $contains = Arr::hasAny($array, ['product.name', 'product.discount']); // true $contains = Arr::hasAny($array, ['category', 'product.discount']); // false ?>
Using Arr::hasAny() in Laravel Controllers
<?php
use Illuminate\Support\Arr;
public function checkUserData(Request $request)
{
$data = $request->all();
if (Arr::hasAny($data, ['name', 'email'])) {
return response()->json(['message' => 'Valid data provided']);
} else {
return response()->json(['error' => 'Missing required fields'], 400);
}
}
?>
Explanation:
Checks if the request contains name or email before processing.