jeudi 8 août 2019

Laravel Validation nullable or numeric

I am using Laravel 5.4.

I have two fields in a form: travel_km and travel_rate

  1. Both fields must be numeric
  2. Both fields are optional but, travel_rate must be entered if travel_km is not empty

My rules: 'travel_km' => 'numeric|nullable', 'travel_rate' => 'sometimes|required_with:travel_km'

The problem is if travel_km is empty I still get an error on travel_rate because it is null.

If I put nullable on travel_rate I do not get an error even if travel_km is not empty.

To solve this I did this in my Controller:

if(empty($request->travel_km) && empty($request->travel_rate)) {
        $this->validate($request,
        [
            'customer_id' => 'required',
            'service_date' => 'required',
            'labour_hrs'    => 'numeric|nullable',
            'hourly_rate' => 'sometimes|required_with:labour_hrs',
        ],
        [
            'customer_id' => 'Please enter the customer',
            'service_date' => 'Please select the service date',
            'labour_hrs' => 'Please enter a valid number',
            'hourly_rate' => 'Please enter a valid number',
        ]);
       } else {
        $this->validate($request,
        [
            'customer_id' => 'required',
            'service_date' => 'required',
            'labour_hrs'    => 'numeric|nullable',
            'hourly_rate' => 'sometimes|required_with:labour_hrs',
            'travel_km' => 'numeric|nullable',
            'travel_rate' => 'sometimes|required_with:travel_km'
        ],
        [
            'customer_id' => 'Please enter the customer',
            'service_date' => 'Please select the service date',
            'labour_hrs' => 'Please enter a valid number',
            'hourly_rate' => 'Please enter a valid number',
            'travel_rate' => 'Please enter a valid number',
            'travel_km' => 'Please enter a valid number'
        ]);
    }

Is there any other way to solve this? I have this issue if a few cases and I don't want to more generic solution.

I looked at Custom Validation but could not understand how do I check if the travel_km is empty or not.

Validator::extend('foo', function ($attribute, $value, $parameters, $validator) {
        return is_numeric($value) && $parameter ????;
    });

Thank you



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire