Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.8 Validation - always bail on any rule

Is there any possibility to set FormRequest rules to default use bail rule without typing in it?

Instead of:

class StoreRequest extends FormRequest {
    function rules() {
        return [
            'name' => 'bail|required|min:3',
            'last_name' => 'bail|required|min:3',
            'names' => 'bail|required|min:3',
            'email' => 'bail|required|email',
            'type' => 'integer|min:10|max:50',
            // [...]
        ];
    }
}

I would like to get more cleaner version, like:

class StoreRequest extends FormRequest {

    protected $stopsOnFirstError = true; // I can't find anything like this

    function rules() {
        return [
            'name' => 'required|min:3',
            'last_name' => 'required|min:3',
            'names' => 'required|min:3',
            'email' => 'required|email',
            'type' => 'integer|min:10|max:50',
            // [...]
        ];
    }
}

Update:

Some of my rules are defined as array:

'type' => [
    'bail',
    'required',
    'integer',
    Rule::in(ContactType::getValues()),
],
like image 815
Daniel Avatar asked Mar 18 '19 07:03

Daniel


People also ask

What is bail in laravel validation?

If you added more than one validation on your field like required, integer, min and max then if the first is fail then the other should stop to display an error message. right now by default, it prints others too. so you can prevent that by using the bail validation rule in laravel.

How does validation work in laravel?

The validate method accepts an incoming HTTP request and a set of validation rules. If the validation rules pass, your code will keep executing normally; however, if validation fails, an exception will be thrown and the proper error response will automatically be sent back to the user.

How do I create a custom validation rule in laravel?

Custom Validation Rule Using Closures $validator = Validator::make($request->post(),[ 'birth_year'=>[ 'required', function($attribute, $value, $fail){ if($value >= 1990 && $value <= date('Y')){ $fail("The :attribute must be between 1990 to ". date('Y').". "); } } ] ]);

What is the method used to configure validation rules in form request?

Laravel Form Request class comes with two default methods auth() and rules() . You can perform any authorization logic in auth() method whether the current user is allowed to request or not. And in rules() method you can write all your validation rule.


3 Answers

1) Without making it more complex use string replacement

<?php
$rules = [
            'name' => 'required|min:3',
            'last_name' => 'required|min:3',
            'names' => 'required|min:3',
            'email' => 'required|email'
        ];
$stopsOnFirstError = true;
if(stopsOnFirstError){
  array_walk($rules, function(&$value, $key) { $value = 'bail|'.$value; } );
}

print_r($rules);
?>

Live Demo : Link

Output :

Array
(
    [name] => bail|required|min:3
    [last_name] => bail|required|min:3
    [names] => bail|required|min:3
    [email] => bail|required|email
)

2) You can also do this in other way , by just adding '*' => 'bail', to apply for all fields

class StoreRequest extends FormRequest {
    function rules() {
        return [
            '*' => 'bail',
            'name' => 'required|min:3',
            'last_name' => 'required|min:3',
            'names' => 'required|min:3',
            'email' => 'required|email',
        ];
    }
}
like image 193
Niklesh Raut Avatar answered Nov 11 '22 00:11

Niklesh Raut


You can always override the validator method in your form request class:

class StoreRequest extends FormRequest {

    private function prependBailOnRule($rule) {
        if (is_string($rule)) {
            return "bail|".$rule;
        } else if (is_array($rule)) {
           return array_merge([ "bail" ], $rule);
        }
    }

    //Adapted from FromRequest::createDefaultValidator
    public function validator(ValidationFactory $factory) {
        return $factory->make(
             $this->validationData(), 
             array_map([$this, 'prependBailOnRule' ], $this->container->call([$this, 'rules'])),
             $this->messages(), $this->attributes()
        );
    }

    function rules() {
        return [
            'name' => 'required|min:3',
            'last_name' => 'required|min:3',
            'names' => 'required|min:3',
            'email' => 'required|email',
            'type' => 'integer|min:10|max:50',
            // [...]
        ];
    }
}
like image 1
apokryfos Avatar answered Nov 10 '22 23:11

apokryfos


Here I'm using Laravel 8 and easily stop the validating on the first error by setting the $stopOnFirstFailure = true;

class StoreRequest extends FormRequest{
protected $stopOnFirstFailure = true;

public function rules()
{
    return [
        'name'      => 'required|min:3',
        'last_name' => 'required|min:3',
        'names'     => 'required|min:3',
        'email'     => 'required|email',
    ];
}

}

like image 1
Md. Morshadun Nur Avatar answered Nov 10 '22 23:11

Md. Morshadun Nur