Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate Unique - TypeError Argument 1 passed to Illuminate\Validation\Factory::make() must be of the type array, null given

Tags:

php

laravel

I have in the User model this method:

public function setDocAttribute($value){
    return $this->attributes['doc'] = $this->clear($value);
}

The clear method:

private function clear(?string $arg){

    if(empty($arg)){
        return '';
    }
    return str_replace(['.','-'], '', $arg);
}

Then I have a class User that extends FormRequest with this rule:

class User extends FormRequest
{
    public function rules()
    {
        return [
            'doc' => (!empty($this->request->all()['id']) ? 'required|unique:users,doc,' . $this->request->all()['id'] : 'required|unique:users, doc'),
            ...
        ];
    }
}

But the unique part of the rule is not working properly because the doc input have pontuation, so it will compare for example "0043-23.00" with "00432300" and its different so the validation passes. To solve this in the User form request the method all() clear the 'doc' input:

public function all($keys = null)
{
    return $this->clear($this->request->all());
}

Method clear():

public function clear($inputs)
{
    $inputs['doc'] = str_replace(['.','-'],'', $this->request->all()['doc']);
    return $inputs;
}

But like this shows an error:

"TypeError Argument 1 passed to Illuminate\Validation\Factory::make() must be of the type array, null given".

Do you know why?

like image 478
John Avatar asked Nov 07 '22 08:11

John


1 Answers

Maybe you missed return in the all method.

And you can use validation rule unique for a simpler check:

public function rules()
{
    return [
        'doc' => [(new Unique('users', 'doc'))->ignore($this->request->get('id'))],
        // ...
    ];
}

like image 68
zlodes Avatar answered Nov 15 '22 04:11

zlodes