• 12
name

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191

Backtrace:

File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 191
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

name Punditsdkoslkdosdkoskdo

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');
    }

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.

  • 12
Reply Report
      • 2
    • Thank you for the response, That's what I was thinking I was just wondering what the community thought. I just got into the laravel framework and even php in general a few months ago at my internship and I love it so I am trying to get into the roots of the framework and learn as much as possible!
      • 1
    • Sounds good. I would try to go through some of the source files and learn from there. You can get a lot of info by looking through some of the base files like Controller.php, Model.php, etc. Some days when I'm bored at work I end up going through that rabbit hole and end up learning something useful.

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

  • 1
Reply Report
      • 1
    • the FormRequest allow you can reuse the rules, most is used on store/update, Route Model Binding if the id not found will throw 404, as you can see i didn't use find(id) on my update method
      • 1
    • I will definitely look over the larvael docs for this and see how I can use it in the application! Thank you so much for the response!

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

  • 1
Reply Report

Validator helper makes me more happy

$validator = validator()->make(request()->all(), [
    'type' => 'required|integer'
]);

if ($validator->fails())
{
    redirect()->back()->with('error', ['your message here']);
}

Laravel give helper that makes developing more convince.

  • 0
Reply Report

Warm tip !!!

This article is reproduced from Stack Exchange / Stack Overflow, please click

Trending Tags

Related Questions