gpt4 book ai didi

php - Laravel 5. 异常处理程序/唯一数据库字段

转载 作者:搜寻专家 更新时间:2023-10-31 21:05:15 25 4
gpt4 key购买 nike

我想避免以下错误:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry

当我尝试添加数据库中已存在的电子邮件时,屏幕上会显示此信息。所以我想用 View 中显示的自定义错误消息替换此错误屏幕。

这是我尝试过的:

//inside app/Exceptions/Handler.php

public function render($request, Exception $e)
{
if ($e instanceof ModelNotFoundException) {
$e = new NotFoundHttpException($e->getMessage(), $e);
}

if ($e instanceof Illuminate\Database\QueryException){
if($e->errorInfo[1] == 1062){
// But It never reaches this point
}
}

return parent::render($request, $e);
}

错误码确实是1062,但是问题是没有通过这个:

if ($e instanceof Illuminate\Database\QueryException)

你知道为什么,或者我做错了什么吗?

最佳答案

If nothing works the worst answer is to remove the unique key from 'email' field in db.

但我认为您需要的是验证,您还可以为每个字段设置自定义错误消息。

引用:http://laravel.com/docs/5.0/validation#custom-error-messages

Controller 文件

public function store(Request $request)
{
$v = Validator::make($request->all(), [
'name' => 'required|min:5',
'email' => 'required|email|unique:users,email',
'password' => 'required|min:6',
'confirm_password' => 'required|min:6|same:password'
]);

if ($v->fails())
{
return redirect()->back()->withErrors($v->errors());
}

//do success actions here
}

关于php - Laravel 5. 异常处理程序/唯一数据库字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33670050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com