Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.6 $this->validate vs Validator::make()

I saw there are a few other questions in which they asked what the difference was between $this->validate and Validator::make(). They didnt really answer the conceptual question I was wondering though.

Is there a proper use for each of these? Like when to use one versus the other?

How I am currently using it is in my API classes I use a if else with $validator::make() (like below) while in my Web portion of the program I use $this->validate() (also below)

Is this a proper way to use this?

$validator::make:

public function store(Request $request)
    {
        $validator = Validator::make($request->all(),[
            'name' => 'required',
            'url' => 'required',
            'isPublic' => 'required'
        ]);

        if($validator->fails()){
            return response($validator->messages(), 200);
        } else {

            Helpers::storeServer($request);

            return response()->json([
                'message'=> ['Server Stored']
            ]);
        }
    }

$this->validate:

 public function store(Request $request)
    {

        $this->validate($request, [
            'name' => 'required',
            'url' => 'required',
            'isPublic' => 'required'
        ]);

        Helpers::storeServer($request);

        return redirect('dashboard')->with('success', 'Server stored');
    }
like image 879
Striker Avatar asked Jul 05 '18 14:07

Striker


3 Answers

Nope, they do the same exact thing two different ways. I mean that literally, $this->validate() calls the make() method on the validation class. If you look at ValidatesRequests.php, implemented by Controller.php which your controller extends.

The validate() method calls:

$validator = $this->getValidationFactory()
             ->make($request->all(), $rules, $messages, $customAttributes);

So it ends up using the make() method eventually. There is a difference in how it is handled, since $this->validate() calls:

if ($validator->fails()) {
    $this->throwValidationException($request, $validator);
}

So using Validator::make() will allow you to handle the exception yourself, instead of $this->validate() auto throwing the validation exception for you. This is useful for doing something before your redirect. You show this in your first example, since you check if the validation fails before deciding how to handle it. In the second example you know that if validation fails it will automatically refuse the request...

like image 106
N Mahurin Avatar answered Oct 21 '22 09:10

N Mahurin


if fail any rules on $this->validate, will auto throw an error

$validator::make: you can easy handle the errors and may be you want wrap any data to array() and pass to $validator::make: for Validation

and also if you want to use FormRequest + Route Model Binding

your store() look like this

public function store(YourFormRequestRules $request)
    {
        Helpers::storeServer($request);

        return redirect('dashboard')->with('success', 'Server stored');
    }

public function update(YourFormRequestRules $request, Post $post)
{
    $post->title = $request->input('title');
    $post->save();
    return redirect()->route('example.index');
}

thats all

like image 25
kenken9999 Avatar answered Oct 21 '22 10:10

kenken9999


Using $this->validate(): YourController extends a Controller class which uses ValidatesRequests trait and it looks like this:

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}

The ValidatesRequests trait itself is made up of several methods that the base Controller gets and then your own controller and which includes:

validateWith($validator, Request $request = null)
...
validate(Request $request, array $rules, array $messages = [], array $customAttributes = [])
...
validateWithBag($errorBag, Request $request, array $rules, array $messages = [], array $customAttributes = [])
... and so on...

These methods helps makes some validation and request errors handling much convenient and in fact considering the mentioned validate() method.

When there's validation error in the request passed, it helps you handle the response without litering your controller with unneeded logic; i.e when it's an ajax call it returns a 422 response with a json body while it returns populates the error bag and fill the $errors variable for use in the blade template for non-ajax.

In summary, this only helps you incase you don't want to do manual validation by creating an instance of Validator, so to keep the developer focus on doing the real work ;)

UPDATE:

$validator = Validator::make() //creates an instance of the validator for further operations

// You can even do after the creating the instance of validator:
$this->validateWith($validator, $request)

//Lets do both steps above i.e the validation and trigger the Validation Exception if there's failure.
$this->validate($request, [...rules...], [...messages..]) 

Check: https://laravel.com/docs/5.6/validation#quick-writing-the-validation-logic

like image 1
Oluwatobi Samuel Omisakin Avatar answered Oct 21 '22 10:10

Oluwatobi Samuel Omisakin