Search code examples
phplaravellaravel-validation

How to use a Request class to validate


How can I validate a request without the dependency injection?

I need to validate two different thing in the same posting. For example, I need to run a basic validation for an entry, but also I need to validate credit card information, the payment method could change, that's why I don't add the credit card data in the basic entry request.

In my method I have:

public method create (EntryRequest $request) {

Validator::make($request->all(), 
[rules] 
}

But I already have my rules in a CreditCardRequest. How can I apply the rules to that request?

Like Validator::make($request->all(), new CreditCardRequest())

Solution

  • You can do conditional validation in form request classes. So if you only wanted to validated credit card fields if payment_method is card, then you could do that like this:

    class StorePaymentRequest extends FormRequest
    {
        public function rules()
        {
            return [
                'payment_method' => ['required', 'in:card,paypal'],
                // Any other basic rules for the request
            ];
        }
    
        public function withValidator($validator)
        {
            // Conditionally add validation for card fields if payment method is card
            $cardFields = ['card_number', 'expiry_date', 'cvc'];
    
            $validator->sometimes($cardFields, 'required', function ($input) {
                return $input->payment_method == 'card';
            });
        }
    }
    

    Documentation: https://laravel.com/docs/5.8/validation#conditionally-adding-rules