Laravel中的异常处理
By admin
- One minute read - 175 wordsEloquent try/catch on duplicate key Exception and delete?
I’ve a form for a new vendor where the controller listens for its POST. From there on I’m creating a new endor and the equivalential login for this vendor.
Controller :
$vendor = Vendor::create( $request->all() );
$login = Vendor::createLogin($vendor->vendor_id);
the createLogin function :
public static function createLogin($lid){
$name = self::find($lid)->vendor_name;
$name = explode(' ', $name);
$vendor_login = [
'username' => strtolower( end($name) ) . '.vendor',
'group' => 'vendor'
];
try{
$user = User::create( $vendor_login );
return $user;
}
catch (Illuminate\Database\QueryException $e){
$error_code = $e->errorInfo[1];
if($error_code == 1062){
self::delete($lid);
return 'houston, we have a duplicate entry problem';
}
}
Creating a new, nonexistant one : works perfectly. However the try/catch block never seems to be reached since I’m always getting laravels inbuild error site with the QueryException for the duplicate entry on the users table. How can I make it work, that on a duplicate entry it deletes the vendor it set before from the table Vendor AND returns an error to display for the user?