Eloquent try/catch on duplicate key Exception and delete?

Published 2 years ago by Yado

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?

EDIT:
I fixed it by adding use Illuminate\Database\QueryException; and catch (QueryException $e)
sigh Sometimes it's the small things..

David-R

@YADO you are the best!!!

Also I just found out that the catch below was fine as well

catch (\Exception $e)

WildChild85

It would be great if there where constants like DB::DUPLICATE_KEY or something similar.

I am a Laravel Newbie, where can I make feature requests? :D

Please sign in or create an account to participate in this conversation.