【问题标题】:Laravel catch Validationexception in custom requestLaravel 在自定义请求中捕获 Validationexception
【发布时间】:2017-04-27 21:37:14
【问题描述】:

我正在 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."]}

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

任何指针?我需要将验证移回控制器吗?还是有更清洁的方法来做到这一点?

【问题讨论】:

    标签: php laravel laravel-5


    【解决方案1】:

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

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

    【讨论】:

    • 是的,看起来可以,我刚刚 var_dumped $errors.. 知道为什么我在 JSON 中有两个错误吗?
    • 只有重复的电子邮件?发送请求而不需要其他字段作为名称
    猜你喜欢
    • 2020-09-30
    • 2019-10-20
    • 2019-08-09
    • 1970-01-01
    • 2017-05-30
    • 2017-10-03
    • 1970-01-01
    • 1970-01-01
    • 2014-11-22
    相关资源
    最近更新 更多