Home > Back-end >  How to update a user only when value has not changed in the database and also avoid using other peop
How to update a user only when value has not changed in the database and also avoid using other peop

Time:12-03

So, I have controller method which validates user and updates their information.

public function updateBasicInfo(Request $request)
    {
        $basic_info = Validator::make($request->all(), [
            'fullname' => 'required|min:2|max:255',
            'phone_number' => 'required|numeric|min:10',
            'email' => 'required',
            'country' => 'required',
            'address' => 'required',
        ], [
            'phone_number.min' => "The phone number must be at least 10 digits",
        ]);

        if($basic_info->fails())
        {
            return response()->json([
                'errors'=> $basic_info->errors()->all(),
            ]);
        }
        else
        {
            $basic_info = $basic_info->validated();
            $user = request()->session()->get('id');
            $currentUser = User::firstWhere('username', $user->username);

            $currentUser->name = $basic_info['fullname'];
            $currentUser->phone_number = $basic_info['phone_number'];
            $currentUser->email = $basic_info['email'];
            $currentUser->save();

            UserDetail::firstWhere(['username' => $user->username])->update([
            'address'=>$basic_info['address'], 
            'country' => $basic_info['country'],
            ]);
            $current_user = $currentUser;
            Mail::to($current_user->email)->send(new ProfileMail($user));
            return response()->json(['success'=> 'Profile Updated Sucessfully']);
        }
    }

I want to update user but I don't want two users to have the same email and I also want the user email to change only if it's value has been changed in the database. Check to make sure that only the user has that email in the whole table and update it to prevent double email records

Please, how do I do this?

I have tried calling the isDirty() method,nothing seems to work

CodePudding user response:

You can use the unique validation rule for email with ignore to make sure that it doesn't receive an error if the new email is the same as the last email. (Unique validation only in comparison with other users). Check out this link.

    $basic_info = Validator::make($request->all(), [
        'fullname' => 'required|min:2|max:255',
        'phone_number' => 'required|numeric|min:10',
        'email' => 'required|unique:users,email,'.request()->session()->get('id'),
        'country' => 'required',
        'address' => 'required',
    ], [
        'phone_number.min' => "The phone number must be at least 10 digits",
    ]);

The isDirty() method is to check if you set a value to any of the properties of instance. And it checks the change after it occured.isDirty()

  • Related