Try catch for laravel 对重复输入不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35648388/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:18:24  来源:igfitidea点击:

Try catch for laravel is not working for duplicate entry

phplaravellaravel-5laravel-5.2

提问by Jija

I am using below code in laravel controller. And getting duplicate error for usernamebut I need to handle it by try-catch. This code is not working.

我在 Laravel 控制器中使用以下代码。并收到重复的错误,username但我需要通过 try-catch 来处理它。此代码不起作用。

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

谢谢你的帮助。

回答by Niklesh Raut

You need to make Exception as global,

您需要将 Exception 设为全局,

  1. Either by using.

    use Exception;
    
  1. 要么通过使用。

    use Exception;
    

and then use

然后使用

catch(Exception $exception)
  1. Or by using

    catch(\Exception $exception)
    
  1. 或者通过使用

    catch(\Exception $exception)
    

Instead of this

而不是这个

catch(Exception $exception)

回答by Idan Ptichi

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

您可以通过首先根据数据库表中的所需列验证用户名的唯一性来轻松避免此 try & catch 块。您可以使用 $request 对象或(更好)通过设置自定义 Request 类来完成此操作,该类将在执行控制器方法之前进行此验证。 https://laravel.com/docs/5.1/validation#rule-unique