Q:

Laravel 5.x. Throwing Manual error from form validations

Is there any way to throw a manual form validation error in laravel. Let's say there's a function that allows to check a credit card's number and if that fails I want to set an error and redirect the user back to the form. I'm looking for something like.
private function validateCreditCard() {...}
if (!validateCreditCard()) {
    # Throw a form validation error here.
}

A:

There are actually many ways of validating in Laravel.

From Controller

Validator::make($request->all(), [
        'ccv' => 'required|numeric|max:3',
        'card_number' => 'required',
     'expiry_date' => 'required',
 ])->validate();

Specify where you want to redirect request to explictly in your code

 $validator = Validator::make($request->all(), [
            'ccv' => 'required|numeric',
            'card_number' => 'required',
             'expiry_date' => 'required',

            
        ]);

        if ($validator->fails()) {
            return redirect('pay/with/creditcard')
                        ->withErrors($validator)
                        ->withInput();
        }

Do another validation after the first validation e.g (check if card is debitable)

$validator = Validator::make(
                'ccv' => 'required|numeric',
                'card_number' => 'required',
                 'expiry_date' => 'required',); //your normal validation here. e.g  ccv, required fields etc.
    
    $validator->after(function ($validator) {
        if (!$this->validateCreditCard()) { //do another validation e.g check if card is debitable
        
            $validator->errors()->add('credit_card', 'Something is wrong with this credit card!');
        }
    });

And you can redirect back to payment form. Let's assume your route is 'pay/with/creditcard'
if ($validator->fails()) {
            return redirect('pay/with/creditcard')
                        ->withErrors($validator)
                        ->withInput();
        }

