2016-12-12 73 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

只有重复的电子邮件?发送请求时不需要其他字段作为名称 –