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 怎样才能让鼠标沿着线条的中心线轨迹移动
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?