8 months ago

Forcing a unique rule to ignore a given id proper way

Posted 8 months ago by boby

I saw there is a 15+ threads about this, but I just can't get it work!

This is my validation for user create and edit:

protected function validateUser()
        $rules = [    
            'username' => ['required', 'string','min:3', 'max:255', 'unique:users'],
            'first_name' => ['required', 'string','min:3', 'max:255'],
            'last_name' => ['required', 'string','min:3', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
            'date_of_birth' => ['required', 'date'],
            'image'  => ['image','mimes:jpeg,png,jpg,gif,svg','max:4098',

        if (! $this->user) {
            $rules['username'] = ['required', 'string', 'min:3', 'max:255'];
            $rules['email'] = ['required', 'string', 'email', 'max:255'];

        return request()->validate($rules);


So I want to ignore id of a current user for a username and email. I have also tried:

'username' => ['required', 'string','min:3', 'max:255', 'unique:users,' . $id]

but that can't find $id ofc as it is not passed to function.

First method complains about Undefined property: App\Http\Controllers\UserController::$user

I just don't know how to make this work

Please sign in or create an account to participate in this conversation.