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

时间:2016-02-26 09:51:17

标签: php laravel laravel-5 laravel-5.2

我在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]);
    }
}

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

来处理
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'test1' for key 'username' 

感谢您的帮助。

2 个答案:

答案 0 :(得分:14)

您需要将Exception设为全局

  1. 使用。

    use Exception;
    
  2. 然后使用

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

      catch(\Exception $exception)
      
    2. 而不是这个

      catch(Exception $exception)
      

答案 1 :(得分:4)

你可以轻松避免这种尝试&amp;通过首先根据db表中的所需列验证用户名的uniqness来捕获块。您可以使用$ request对象或(更好)通过设置自定义Request类来执行此操作,该类将在执行控制器方法之前执行此验证。 https://laravel.com/docs/5.1/validation#rule-unique

相关问题