php – 尝试catch for laravel不能用于重复输入

前端之家收集整理的这篇文章主要介绍了php – 尝试catch for laravel不能用于重复输入前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在laravel控制器中使用下面的代码.并获得用户名的重复错误,但我需要通过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]);
    }
}

我收到此错误,我需要通过try和catch来处理

sqlSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'test1' for key 'username'

谢谢你的帮助.

解决方法

你需要将Exception设为全局,

>通过使用.

use Exception;

然后使用

catch(Exception $exception)

>或者通过使用

catch(\Exception $exception)

而不是这个

catch(Exception $exception)

猜你在找的Laravel相关文章