Raheel
Raheel

Reputation: 9024

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 ?

Upvotes: 3

Views: 4607

Answers (2)

Jonathan
Jonathan

Reputation: 11494

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.

Upvotes: 4

Bogdan
Bogdan

Reputation: 44526

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']

Upvotes: 2

Related Questions