Waleed
Waleed

Reputation: 73

laravel 7 profile udpate wiith email unique:users

I am trying to update the user profile. Everything works good but when i try to update name without updating the email. It gives an error saying the email already exists. I have tried the method in the docs too but it does not work. I am using laravel 7 Here is my code

        $userId = auth()->user()->id;
    $validate = $request->validate([
        'name' => 'required|string',
        'email' => ['required', Rule::unique('users')->ignore($userId)],
        'password' => 'required|',
    ]);

    $user = User::find(auth()->user()->id);
    $password = $request->password;

    $user::create([
        'name' => $validate['name'],
        'email' => $validate['email'],
        'password' => Hash::make($password),
    ]);

Note: I just fixed it

I was not updating the profile i was creating a new one. I was using $user::create but this code creates another row in table the which is why the validation was not working so i replaced it with this code

       $user->name = $request->name;
    $user->email = $request->email;
    $user->password = Hash::make($password);
    $user->save();

Now it works.

Upvotes: 0

Views: 121

Answers (1)

viryl15
viryl15

Reputation: 564

you can use update in place of create like this:

$user::update([
    'name' => $validate['name'],
    'email' => $validate['email'],
    'password' => Hash::make($password),
]);

Upvotes: 3

Related Questions