Yado

Eloquent try/catch on duplicate key Exception and delete?

Posted 3 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..

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

Laracasts Mascot

Hi, Have We Met Yet?

Did you know that, in addition to the forum, Laracasts includes well over 1000 lessons on modern web development? All for the price of one lunch out per month.

Sign Me Up

Channels

Reply to

Use Markdown with GitHub-flavored code blocks.