Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try catch for laravel is not working for duplicate entry

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.

like image 747
Jija Avatar asked Feb 26 '16 09:02

Jija


2 Answers

You need to make Exception as global,

  1. Either by using.

    use Exception;
    

and then use

catch(Exception $exception)
  1. Or by using

    catch(\Exception $exception)
    

Instead of this

catch(Exception $exception)
like image 163
Niklesh Raut Avatar answered Nov 07 '22 07:11

Niklesh Raut


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

like image 33
Idan Ptichi Avatar answered Nov 07 '22 07:11

Idan Ptichi