Laravel check for constraint violation

后端 未结 5 2109
野的像风
野的像风 2021-02-05 11:15

I was curious if there is a way we can check if there is a constraint violation error when delete or insert a record into the database.

The exception thrown is called \'

5条回答
  •  悲哀的现实
    2021-02-05 12:13

    first put this in your controller

    use Exception;
    

    second handle the error by using try catch like this example

    try{    //here trying to update email and phone in db which are unique values
            DB::table('users')
                ->where('role_id',1)
                ->update($edit);
            return redirect("admin/update_profile")
                   ->with('update','update');
                }catch(Exception $e){
                 //if email or phone exist before in db redirect with error messages
                    return redirect()->back()->with('phone_email','phone_email_exist before');
                }
    

    New updates here without need to use try catch you can easily do that in validation rules as the following code blew

    public function update(Request $request, $id)
    {
        $profile = request()->all();
        $rules    = [
                'name'                       => 'required|unique:users,id,'.$id,
                'email'                      => 'required|email|unique:users,id,'.$id,
                'phone'                      => 'required|unique:users,id,'.$id,
        ];
        $validator = Validator::make($profile,$rules);
        if ($validator->fails()){
            return redirect()->back()->withInput($profile)->withErrors($validator);
        }else{
            if(!empty($profile['password'])){
                $save['password'] = bcrypt($profile['password']);
            }
            $save['name']                  = $profile['name'];
            $save['email']                 = $profile['email'];
            $save['phone']                 = $profile['phone'];
            $save['remember_token']        = $profile['_token'];
            $save['updated_at']            = Carbon::now();
    
            DB::table('users')->where('id',$id)->update($save);
            return redirect()->back()->with('update','update');
        }
    }
    

    where id related to record which you edit.

提交回复
热议问题