skip to Main Content

i tried to ignore code when user trying to modify his profile, but throw me error: Code already exists.

Here is my code:

Table: users

id       email
1 [email protected] 
2 [email protected]
3 [email protected]
4 [email protected]

Table: profiles

id        user_id          code 
1            3             er1254
2            4             zk1299



$validatedData = $this->validate([
    'code' => 'required|unique:profiles,code,'.Auth::user()->id,
]);

always give me this code already exists… what’s wrong with my validation please? I want to ignore verification to allow user modify his profile without changing the code.

2

Answers


  1. I would suggest you try the Rule::unique().

    Here is what that might look for your example.

    $validateData = this->validate([
        "code" => "required|".Rule::unique('code')->ignore(request()->id)
    

    This would allow you to update the record and ignore the unique requirement if it has the same id.

    Note, you may need to modify the code to suit your specific needs.

    Login or Signup to reply.
  2. you should update your validation like this:

    $validatedData = $this->validate([
        'code' => [
            'required',
            Rule::unique('profiles', 'code')->where(function ($query) {
                return $query->where('user_id', Auth::user()->id);
            })->ignore(Auth::user()->profile->id),
        ],
    ]);
    

    The profile in Auth::user()->profile->id is assumed to be a relationship between the User model and the Profile model.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search