Laravel validation after() - expects parameter 1 to be a valid callback

Viewed 120

I am not good at programming, but I am this far with validation in Laravel:

$validator = \Validator::make($post_data, $rules);
$validator->after(\App\Helpers\PostHelpers::validatePostTitle($validator, $request));

I have been told not to repeat myself. How do I use the after() function with the required parameters in a helper class?

    namespace App\Helpers;
    
    class PostHelpers
    {
        public static function validatePostTitle($validator, $request) {
            // do some magic
        }
    }

Laravel said:

call_user_func_array() expects parameter 1 to be a valid callback, no array or string given

at:

    public function after($callback)
    {
        $this->after[] = function () use ($callback) {
            return call_user_func_array($callback, [$this]);
        };
 
        return $this;
    }
1 Answers

The function after requires a callback as an argument. One of these forms should work:

$validator->after(function ($validator, $requst) { 
     return \App\Helpers\PostHelpers::validatePostTitle($validator, $request) 
});

or

$validator->after([\App\Helpers\PostHelpers::class, 'validatePostTitle' ]);

More detail on PHP callables can be found in the manual

Related