Search code examples
phplaravelvalidation

I need to validate a query parameter


The query parameter is status It's value can be status=draft or status=draft,sent&

How can I validate that the status is draft, sent or approved?

I was using this rule

'status'    => 'nullable|in:draft,approved,declined,sent'

To validate statuses invidually. How can I validate if there are 2 status and they're valid?


Solution

  • You can extend Laravel validation in your AppServiceProvider in boot() method like so

    Validator::extend('check_status', function ($attribute, $value, $parameters, $validator) {
        $valid_statuses = ['draft', 'approved', 'declined', 'sent'];
        $requested_statuses = explode(",", $value);
        $array_diff = array_diff($requested_statuses, $valid_statuses);
    
        $validator->addReplacer('check_status', function ($message, $attribute, $rule, $parameters) use ($array_diff) {
             return str_replace(':statuses', implode(", ", $array_diff), $message);
        });
    
        return empty($array_diff);
    }, 'Statuses [:statuses] are not valid');
    

    i have added a custom validation error message that will print all not valid statuses.

    in your controller you will add

    'status' => 'nullable|check_status'