Search code examples
laravellaravel-validation

Laravel validator after method running before the validation


I have validation rules in the below

public function rules()
{
    return [
        'ports' => 'required|array|min:2|max:10',
        'ports.*.id' => 'required|distinct|exists:ports,id',
        'ports.*.order' => 'required|distinct|integer|between:1,10',
    ];
}

and the withValidator method

public function withValidator($validator)
{
    // check does order numbers increasing consecutively
    $validator->after(function ($validator) {
        $orders = Arr::pluck($this->ports, 'order');
        sort($orders);

        foreach ($orders as $key => $order) {
            if ($key === 0) continue;

            if ($orders[$key - 1] + 1 != $order) {
                $validator->errors()->add(
                    "ports.$key.order",
                    __('validation.increase_consecutively', ['attribute' => __('validation.attributes.order')])
                );
            };
        }
    });
}

If the client doesn't send the ports array, Arr:pluck method throwing an exception because of $this->ports equal to NULL. How can I call this code block after validation completed in formRequest?


Solution

  • Try to write in

    if ($validator->fails())
    {
        // Handle errors
    }
    

    Ex.

    public function withValidator($validator)
    {
      if ($validator->fails())
      {
        $orders = Arr::pluck($this->ports, 'order');
        sort($orders);
    
        foreach ($orders as $key => $order) {
           if ($key === 0) continue;
    
           if ($orders[$key - 1] + 1 != $order) {
               $validator->errors()->add(
                   "ports.$key.order",
                   __('validation.increase_consecutively', ['attribute' => __('validation.attributes.order')])
               );
           };
        }
      }
    }