Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel In Array validation

I am trying to validate a payment methods field.

Requirement is the field under validation must be of type array (Multiple values allowed) and the items should not be other than the defined option

'payment_method' => 'required|array|in:american_express,cash_on_delivery,paypal,paypal_credit_card,visa_master_card'

So the user should pass an array of values for e.g

array('american_express','paypal');

But should not pass

array('american_express', 'bank');

I am unable to find any such method in Laravel 4.1 documentation. Is there any work around for this ?

like image 561
Raheel Avatar asked Apr 22 '26 18:04

Raheel


2 Answers

If you're using a later version of Laravel (not sure when the feature becomes available - but certainly in 5.2) you can simply do the following:

[
    'payment_method' => 'array',
    'payment_method.*' => 'in:american_express,cash_on_delivery,paypal,paypal_credit_card,visa_master_card'
];

You check that the payment_method itself is an array if you like, and the star wildcard allows you to match against any in the array input.

You might consider putting this into the rules() method of a request validator (that you can generate with php artisan make:request PaymentRequest as an example.

like image 147
Jonathan Avatar answered Apr 25 '26 07:04

Jonathan


You can actually extend the Laravel validator and create your own validation rules. In your case you can very easily define your own rule called in_array like so:

Validator::extend('in_array', function($attribute, $value, $parameters)
{
    return !array_diff($value, $parameters);
});

That will compute the difference between the user input array found in $value and the validator array found in $parameters. If all $value items are found in $parameters, the result would be an empty array, which negated ! will be true, meaning the validation passed. Then you can use the rule you already tried, but replace in with in_array like so:

['payment_method' => 'required|array|in_array:american_express,cash_on_delivery,paypal,paypal_credit_card,visa_master_card']
like image 42
Bogdan Avatar answered Apr 25 '26 08:04

Bogdan