Search code examples
phpvalidationlaravel-5laravel-5.8

What is the difference between validate() and validated() function in Laravel 5.8, PHP?


I could not find the different definition between the validate() and validated() function in the documentation on laravel.com website.

But in the Validator interface file, I have read the comment of the function as following:

/**
 * Run the validator's rules against its data.
 *
 * @return array
 */
public function validate();

/**
 * Get the attributes and values that were validated.
 *
 * @return array
 */
public function validated();

I do understand these comments, but when I write the code and test both functions, I did not see any difference. Both seem to act the same:

  1. validates data.
  2. if failed, redirects users to their previous page.
  3. if succeeded, return validated data in an array.

So, what is the difference between these two function in Laravel 5.8?

In my case, I use the validation as following, because I do not want to redirect users back to their previous page when validation failed.

$validator = validator($array_data, $array_rules, $array_message);

if ($validator->fails()) {
    // Do something
} else {
    $validated_data = $validator->validate();
    // Here I am not sure if I should use the validated() function, because I do not see the difference between these two functions.
    // $validated_data = $validator->validated();    
}

Solution

  • Looks like it's safe to use either, at least currently. Here's the source for validate():

    public function validate()
    {
        if ($this->fails()) {
            throw new ValidationException($this);
        }
    
        return $this->validated();
    }
    

    As you can see, the return value is the results of validated().

    That said, I'd personally use validate() to perform validation, and validated() to get the validated data. This should insulate you from potential future changes to the validate() function (if it were, say, changed to return a true/false instead) and result in slightly more readable code.