Try catch for laravel is not working for duplicate entry
11,652
Solution 1
You need to make Exception as global,
-
Either by using.
use Exception;
and then use
catch(Exception $exception)
-
Or by using
catch(\Exception $exception)
Instead of this
catch(Exception $exception)
Solution 2
you can easily avoid this try & catch block by first validating the uniqness of the username against the desired column in your db table. you can do it with your $request object or (better) by setting a custom Request class that will do this validation before excecution the controller method. https://laravel.com/docs/5.1/validation#rule-unique
Author by
Jija
Updated on June 09, 2022Comments
-
Jija almost 2 years
I am using below code in laravel controller. And getting duplicate error for
username
but I need to handle it by try-catch. This code is not working.<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; use Response; use DB; class StaffController extends Controller { public function saveMember(Request $request){ $errormsg = ""; $result = false; try{ $result = DB::table('members')->insert( [ 'username' => $request->username, 'phone' => $request->phone, 'status' => 1 ] ); }catch(Exception $exception) { $errormsg = 'Database error! ' . $exception->getCode(); } return Response::json(['success'=>$result,'errormsg'=>$errormsg]); } }
I am getting this error, which I need to handle by try and catch
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'test1' for key 'username'
Thanks for your help.
-
Jija about 8 yearsYes, I will apply you suggestion later, but my question was why try-catch is not working, although it solved, thanks for your ans.
-
John Little over 6 yearsWhy does this work? I.e. why is catch(Exception $exception) failing to catch the exception?
-
Niklesh Raut over 6 years@JohnLittle : Are you able to catch error with
catch(Exception $exception)
without usinguse Exception;
at the top ? Or you are pointing to any other thing ? -
John Little over 6 yearsI was trying just "catch(Exception $exception)" without "use Exception". I changed it to "catch(\Exception $exception)" and it worked. I would have assumed that if Exception was not resolved, it would have thrown an error when it parses the try/catch? Is \Exception clarifying the namespace? Is \ not default?
-
elfif over 5 yearsEven if i really like Laravel, i think using try/catch and an exception to detect possible duplicate is the most robust solution, hands down. Using a validation is cool and will prevent the issue in most case but you need to think about concurrency with a lot of connections and users. Even if it's unlikely shit can happen... Or someone might just try to make it crash using that kind of tricks.
-
Synchro about 3 yearsThis approach creates a race condition. The only certain way to avoid that is to use a transaction that wraps both your validation check and the insert/update.