dongleman4760 2016-11-08 16:57
浏览 72
已采纳

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?

  • 写回答

1条回答 默认 最新

  • dongyao5186 2016-11-08 17:09
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)