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.
JavaScript
x
<?php
namespace AppHttpControllers;
use IlluminateHttpRequest;
use AppHttpRequests;
use AppHttpControllersController;
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
JavaScript
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'test1' for key 'username'
Thanks for your help.
Advertisement
Answer
You need to make Exception as global,
Either by using.
JavaScriptuse Exception;
and then use
JavaScript
catch(Exception $exception)
Or by using
JavaScriptcatch(Exception $exception)
Instead of this
JavaScript
catch(Exception $exception)