Search code examples
laravelvalidationrules

Rule object doesn't fire passes() method


I am trying to implement validations with Rules to validate a field in a model; as indicated in the official documentation, in this way:

1) In the folder App/Rules I put the file Um.php:

<?php
 namespace App\Rules;
 use Illuminate\Contracts\Validation\Rule;
 use App\Models\Common\Item;
 class Um implements Rule
  {

/**
 * Determine if the validation rule passes.
 *
 * @param  string  $attribute
 * @param  mixed  $value
 * @return bool
 */
public function passes($attribute, $value)
{
    if(strlen($attribute) < 5)
    return false;

    return true;
}

/**
 * Get the validation error message.
 *
 * @return string
 */
public function message()
{
    return 'The field is too short ';
}

}

2) In my controller class, in the method update:

 use App\Rules\Um as RuleUm;

...

  public function update(Request $request $item)
{
   //$item is the model don't worry for this 


   //Here is where I invoke the rule 
    $request->validate([
'codum' => [ new RuleUm],
            ]);


    $item->update($request->input());

  //...son on
}

So far so good, the problem comes when after updating the data; the passes () method is totally ignored; and happens to execute the update. This does not depend on the logic of the method because it still returns false in any case, just as Laravel is still ignoring the method, it is not executed.

Can someone help me? What am I doing wrong?


Solution

  • If you are working on custom Rule class, it will not validate if the field(codum in your case) is empty or isn’t present in the request. If you want a custom validation object to run even with the value is empty, you need to use the ImplicitRule contract.

    See this article for the same

    In short you need to do :

    class Um implements ImplicitRule