You can achieve this by creating a custom validation rule. Laravel provides a way to create custom validation rules using the Rule facade. Here's how you can do it:
First, create a new rule using the make:rule artisan command:
php artisan make:rule SectionsDetailsRule
This command will create a new rule class in the app/Rules directory. In this class, you can define your custom validation logic. Here's an example:
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class SectionsDetailsRule implements Rule
{
private $sections;
public function __construct($sections)
{
$this->sections = $sections;
}
public function passes($attribute, $value)
{
if (count($value) != $this->sections) {
return false;
}
foreach ($value as $section) {
if (!isset($section['key1']) || !isset($section['key2'])) {
return false;
}
}
return true;
}
public function message()
{
return 'The :attribute does not match the sections or does not contain the required keys.';
}
}
In the passes method, we first check if the count of the array matches the sections value. Then we loop through each item in the array and check if the required keys exist.
Now you can use this rule in your validation rules method:
public function rules()
{
return [
'sections' => 'required|numeric',
'sections_details' => ['required', 'array', new SectionsDetailsRule($this->sections)],
];
}
This will ensure that the sections_details array has the same count as the sections value and each item in the array contains the required keys.