'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.



Solution 1:[1]

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

Solution 2:[2]

according to this sample:

public function store(ServiceStoreRequest $request, int $id)
{
    $service = new Serviceable();
    $service->package_id = $id;
    $service->fill($request->all());
    try {
        $service->save();
    } catch (\Exception $exception) {
        return response(array(
            "code"=> 409,
            "error"=>"duplicate " . $exception->getMessage()));
    }
    return response($service);
}

Solution 3:[3]

   if($request->isMethod('post')){
        $data       = $request->all();
        $user       = Auth::user()->id;
        try {
            DB::beginTransaction();
            Company::Save($data,$user);
            BankBranch::updateBranch($data,$user,$id);
            DB::commit();
            $status = true;
        } catch (\Exception $e) {
            var_dump('Exception Message: '. $e->getMessage());
            var_dump('Exception Code: '. $e->getCode());
            var_dump('Exception String: '. $e->__toString());
            DB::rollback();
            $status = false;
        }
    }

Solution 4:[4]

The structure has been written for one dataCollectionForm when you multiple tabs, were every one needs a form. Unless on tab change you recreate the form, this should not work.

  1. dataCollectionForm should be a collection of form group, by some id.
  2. Don't over complicate with incorrect user of map

Sudo Code below, might need correction , just there to give you direction:

 public makeLineData: any[] = []; // object with otherDetails

   // will contain form based on myObj index
   public dataCollectionForm: FormGroup[] = []; // in template loop over this by index

 createForm() { // getMakeLineData name correction

    myObj
   .filter(m => m.otherDetails)
   .forEach((obj) => {
     // create and push From in dataCollectionForm
     this.makeLineData.push(obj);
     let dataFrom =  this.addTabDataCollectionForm();

     obj.otherDetails.forEach((detail) => {
       if (detail.processTechType === 'Continuous') {
            this.addQuantity(dataFrom);
          }
          else if (detail.processTechType === 'Batch')  {
            this.addBatch(dataFrom);
          } 
     })

   
   })

    var otherDetails = myObj.filter(m => m.otherDetails).map(m => m.otherDetails);
    this.makeLineData = myObj;
    if (otherDetails) {
      otherDetails.forEach(element => {       
        for (var i of element) {
          if (i.processTechType === 'Continuous') {
            this.addQuantity();
          }
          else if (i.processTechType === 'Batch')  {
            this.addBatch();
          } 
        }
      });      
    } 
}

addTabDataCollectionForm (): FromGroup {
  // this will represet the form of one single tab;
  let tabDataForm = this.fb.group({
      continuousType: new FormArray([])
      batchType: new FormArray([])
    });

    this.dataCollectionForm.push(tabDataForm); 
    return tabDataForm; 
    
}

createContinuousForm() {
    return this.fb.group({
      designProcess: ['', [Validators.required]]
    });
  }
  createBatchForm() {
    return this.fb.group({
      avgBCT: ['', [Validators.required]]
    });
  } 

  continuousType(dataFrom): FormArray {
    return dataFrom.get("continuousType") as FormArray;
  }

  batchType(dataFrom): FormArray {
    return dataFrom.get("batchType") as FormArray;
  }

  addQuantity(dataFrom) {
    this.continuousType(dataFrom).push(this.createContinuousForm());

  }
  addBatch(dataFrom) {
    this.batchType(dataFrom).push(this.createBatchForm());
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Idan Ptichi
Solution 2 saber tabatabaee yazdi
Solution 3 Mohammad Ali Abdullah
Solution 4