2016-12-12 100 views
0

我在Laravel中構建了一個API,並且正在使用自定義請求來驗證入站數據。我的問題是,我不知道我如何「捕捉」驗證錯誤來形成響應。Laravel在自定義請求中捕獲驗證異常

這是我到目前爲止。

註冊方法包裹在一個交易:

//Create User Request extends standard request. Handles Validation 

    public function __construct(CreateUserRequest $request){ 
     $this->request = $request; 
    } 

    public function register() 
    { 
    try{ 

     $array = DB::transaction(function(){ 

      $email = $this->request->input('email'); 
      $password = $this->request->input('password'); 
      $companyName = $this->request->input('companyName'); 
      $userName = $this->request->input('name'); 
      $country = $this->request->input('country'); 

      $company = Company::create([ 
       'name' => $companyName, 
       'active'=>true, 
       'country_id'=>$country 
      ]); 

      $user = User::create([ 
       'company_id' => $company->id, 
       'name'=>'admin', 
       'email' => $email, 
       'password' => $password, 
       'active' =>true 
      ]); 

      if(!$company || !$user) 
      { 
       throw new \Exception('User not created for account'); 
      } 

      return compact('company', 'user'); 
      }); 

     $token = JWTAuth::fromUser($array['user']); 
     return Response::json(compact('token')); 

    } 
    catch(Exception $e) 
    { 
     return Response::json(['error' => $e->getMessage() ], HttpResponse::HTTP_CONFLICT); 
    } 

    } 

形式請求如下所示:

class CreateUserRequest extends FormRequest 
{ 
    /** 
    * Determine if the user is authorized to make this request. 
    * 
    * @return bool 
    */ 
    public function authorize() 
    { 
     return true; 
    } 

    /** 
    * Get the validation rules that apply to the request. 
    * 
    * @return array 
    */ 
    public function rules() 
    { 
     return [ 
      'email' => 'required|unique:users', 
      'password' => 'required', 
      'companyName' => 'required', 
      'name' => 'required', 
      'country' => 'required|numeric' 
     ]; 
    } 
} 

我的錯誤會自動回來了,這似乎是序列化到JSON

的messagebag對象
{"email":["The email has already been taken."]}{"email":["The email has already been taken."]} 

某處在那裏我需要趕上例外,我在主控制器的旁邊,但我已經使用自定義請求類來清理我的控制器了,我該怎麼做?請注意,此控制器中已經捕獲了異常,但似乎無法獲取自定義請求中幕後引發的任何內容。

任何指針?我是否需要將驗證移回控制器?還是有更乾淨的方法來做到這一點?

回答

2

可以覆蓋響應方法CreateUserRequest定製響應:

public function response(array $errors) 
{ 
    return parent::response($errors); 
} 
+0

是啊,看起來像它會做的,我只是var_dumped $錯誤..任何想法爲什麼我在JSON中可能有兩個錯誤? – Paul

+0

只有重複的電子郵件?發送請求時不需要其他字段作爲名稱 –