I need to extend laravel validator creating a new validator but the problem is that I need to pass 2 parameters, one for days
and one for slots
. How to solve this?
Example dd($request->all)
dump:
array:2 [
"days" => array:2 [
0 => "1" // Mon
1 => "2" // Tue
]
"slots" => array:2 [
1 => array:2 [
"open" => "09:00"
"close" => "11:30"
]
2 => array:2 [
"open" => "16:00"
"close" => "21:00"
]
]
]
It need to loop through days
and check with slots
.
Pseudo code, example:
foreach($days as $day) {
foreach($slots as $slot)
{
// Validation Logic for $day and $slot (open and close)
}
}
This is the correct method of making a custom Laravel Validation
Create your own Validation Service Provider using
php artisan make:provider ValidationServiceProvider
then go to config\app.php
and add this to providers
App\Providers\ValidationServiceProvider::class
Now go to ValidationServiceProvider.php
and add
use Validator;
to the top...
and this in the boot()
function
Validator::extend('days_with_slots', function($attribute, $value, $parameters, $validator) {
$slots = request()->get('slots');
if(!is_array($slots)) return false;
foreach($days as $day) {
foreach($slots as $slot) {
if(empty($slot[$day]) || empty($slot[$day]['open'] || empty($slot[$day]['close']))) {
return false;
}
}
}
});
Finally, use this in your rules
$rules['slots'] = 'days_with_slots'
You can also add a custom message for it, say
$message['days_with_slots'] = 'Open and Close Timings are required for the days selected'
Hope this helps :)