Laravel在自定义请求

时间:2016-12-12 22:23:58

标签: php laravel laravel-5

我正在Laravel中构建API,并使用自定义请求来验证入站数据。我的问题是,我不确定如何“捕获”验证错误以形成响应。

这是我到目前为止所拥有的。

包含在事务中的注册方法:

 //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."]}

在那里的某个地方我需要在主控制器中捕获异常,但是我已经使用自定义请求类来清理我的控制器了,我该怎么做?请注意此控制器中已捕获的异常,它似乎不会拾取自定义请求中幕后抛出的任何内容。

任何指针?我需要将验证移回控制器吗?或者有更清洁的方法吗?

1 个答案:

答案 0 :(得分:2)

您可以覆盖 CreateUserRequest 中的响应方法来自定义响应:

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