I created a custom rule with php artisan make:rule, set it in controller, but it not working. What the problem can be?
class CheckDeliveryDate implements Rule
{
public $client_id;
private $is_after_midday;
private $error_messge;
public function __construct(int $client_id)
{
$this->client_id = $client_id;
$this->is_after_midday = Carbon::now()->greaterThan(Carbon::now()->midDay());
$this->error_messge = 'Error';
}
public function passes($attribute, $value)
{
$delivery_date = Carbon::parse($value);
if ($delivery_date->isToday()) {
$this->error_messge = 'Error';
return false;
}
if ($delivery_date->endOfDay()->isPast()) {
$this->error_messge = 'Error';
return false;
}
return true;
}
public function message()
{
return $this->error_messge;
}
}
In controller i set method rules:
public function rules($client_id)
{
return [
'orders.*.positions.*.delivery_time' => [
'required',
'date',
new CheckDeliveryDate($client_id)
],
];
}
and when i store my order, validator->fails() return me "false".
$validator = Validator::make(
$request->all(),
$this->rules($client_id)
);
I tried set dd or dump in Rule, not working. Where is my mistake?
As stated on laravel documentation (https://laravel.com/docs/5.8/validation#custom-validation-rules) you are not supposed to pass the parameter to your custom rule instance. Laravel does it for you.
Thus:
new CheckDeliveryDate($client_id)
Becomes :
new CheckDeliveryDate
Have a nice day !
Wrong JSON format date. This is amazing mistake...