Laravel Eloquent Catch特殊例外

I'm currently trying the following: In my db, I have a column called templateURL, which is a unique key, so it may only exist once. Then if something tries to submit a form, where this is the same as already exist an error is thrown, saying Integrity constraint violation: 1062 Duplicate entry for key 'templateURL'.

Of course it does, that's why I made the column unique. But: What I want is not the default Laravel Error, but getting back to the form with the values still entered and a message (alert from bootstrap for example or just a div next to the input field) saying that this already exist and asking to chooose another one. So I need to catch this exception and do something custom instead. How can I achieve what I want?

You've to wrap your database operation into a try-catch block and catch the error and do something else when you get a error, maybe redirect with old input data with a error message.

The error code for duplicate entry is 1062. So if you get 1062 as error code that means this data is a duplicate entry. Here is the code look like for catching this exception.

try {

    $data = Model::create(array(
      'templateURL' => 'some value ',
    ));

} catch (Illuminate\Database\QueryException $e) {
    $errorCode = $e->errorInfo[1];
    if($errorCode == 1062){
      // we have a duplicate entry problem
    }
}

Or if you wish not to handle the exception yourself, you can take help of Laravel Validator. Like following in your controller

// validation rules
$rules = array(
    'templateURL'            => 'unique:YourTableNameHere'
);

$validator = Validator::make(Input::all(), $rules);

// check if the validation failed
if ($validator->fails()) {

    // get the error messages from the validator
    $messages = $validator->messages();

    // redirect user back to the form with the errors from the validator
    return Redirect::to('form')
        ->withErrors($validator);

} else {

    // validation successful

    $data = Model::create(array(
      'templateURL' => 'some value ',
    ));
}

Then in your view template you can access the error messages via $errors variable. Learn more about validation there https://laravel.com/docs/5.3/validation