5

Here is my model code trying to handle duplicate entries:

$userData = ['name' => $name, 'email' => $email, 'password' => $password]; 

   public function addUser($userData) {     
        try {
            DB::table('users')->insert($userData);
        } catch (QueryException $e) {
            $errorCode = $e->errorInfo[1];          
            if($errorCode == 1062){
                throw ('Duplicate Entry');
            }
        }
    }

Calling controller code looks like: $userModel->addUser($userData);

Here I am not trying to print any response received from model.

Getting error as:

enter image description here

What am I doing wrong? How to handle Exceptions correctly and what's the best practise of doing it?

halfer
  • 19,824
  • 17
  • 99
  • 186
Mithun Shreevatsa
  • 3,588
  • 9
  • 50
  • 95

4 Answers4

13

I was very near to my answer, it was all about namespace issue and error display issue:

Illuminate\Database\QueryException $e should be: \Illuminate\Database\QueryException $e

        try {
            DB::table('users')->insert($userData);  
        } catch(\Illuminate\Database\QueryException $e){
            $errorCode = $e->errorInfo[1];
            if($errorCode == '1062'){
                dd('Duplicate Entry');
            }
        }

return and throw for error did not work, but 'dd' method worked. So this saves my time in querying twice to identify the duplicates and insert and am happy for it :)

Mithun Shreevatsa
  • 3,588
  • 9
  • 50
  • 95
3

You should try this:

public function addUser($userData) 
{     
  try {
    DB::table('users')->insert($userData);
  } catch (Illuminate\Database\QueryException $e){
    $errorCode = $e->errorInfo[1];
    if($errorCode == 1062){
        return 'Duplicate Entry';
    }
  }
}

For more details, please follow this link.

halfer
  • 19,824
  • 17
  • 99
  • 186
AddWeb Solution Pvt Ltd
  • 21,025
  • 5
  • 26
  • 57
2

If you just want to avoid the duplicate entry exception without having to wrap everything between try{} catch{}, you could simply use Laravel's firstOrCreate() method as follows:

User::firstOrCreate([
    'email' => $request->email // unique field here
], $userData);

Using this method assumes that you are calling protected $guarded = [] on your User model.

Waiyl Karim
  • 2,810
  • 21
  • 25
0

public function rules() {

    return [
                    
        'tool_id' => ['required','integer','unique:assign_toolto_joborders'],
        'joborder_id' => ['required','integer'],
        'assign_date' => ['required','date_format:d-m-Y'],
        'tool_qty' => ['required','integer']
        
    ];
}