Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel validator::make vs this->validate()

Tags:

laravel

I have a validator in my controller which works fine (see below).

$this->validate($request,[
        'name' => 'required|alpha',
        'sport' => 'required|alpha',
        'gender' => 'required|alpha',
        'age' => 'required|numeric',
        'score' => 'required|numeric',
]);  

When I get to my view, I just run this:

@if(count($errors) > 0)
    <div>
        <ul>
            @foreach($errors->all() as $error)
                {{ $error }}
            @endforeach
        </ul>
    </div>
@endif

The Laravel documentation uses Validator::make($request...) which one is better in terms of good practice and also performance? The method I used comes from a Laravel 5 Youtube tutorial series.

like image 506
louisav Avatar asked Dec 05 '22 17:12

louisav


1 Answers

If you use $validator = Validator::make(... you then have to check if the validation fails or passes if ($validator->fails()) {... and manually return a response from the controller. So this is useful if you want to redirect somewhere, do something before rendering the view, do something with the errors or any other action you want to perform before returning a response from the method.

The validate() method which is available to all controllers will automatically check if the validation fails based on the data and the rules you provided. If the validation fails a ValidationException is thrown which is automatically handled and the request redirects back with the error from the validation. So this is useful if you have a standard validation and you want to just validate and show the errors in the view.

like image 83
thefallen Avatar answered May 22 '23 04:05

thefallen