Search code examples
phplaravellaravel-validation

Pass current instance to validator in laravel


In laravel 5.3 can I pass as parameter for rule current instance of model?

I want the rule which checks current value of some field in my model and allows or denies to set this field to another value.

The problem is: validator receives only new value, but I also want to check old value.


Solution

  • If this is still necessary:

    You can use fourth argument $customAttributes of the static method Illuminate\Support\Facades\Validator::make. In this argument you can pass anything you want, in your case - specific instance of the model:

    $order = new Order(); // <!-- create or load for DB instance of your model
    
    /*
     * create validator for validation of the some $requestForValidation
     * by some $validationRules
    */
    $validator = \Illuminate\Support\Facades\Validator::make($requestForValidation,
    $validationRules, [], [
        'instance' => $order,
    ]);
    

    And in your custom validation rule you can reach this custom attributes like this:

    Validator::extend('customValidationRule', function ($attribute, $value, 
    $parameters, $validator) {
        $validator->customAttributes['instance']; // <!-- here is your instance
    });