1
votes

I'm building an API in Laravel, and am using a custom request to validate the inbound data. My problem is that I'm not sure how I 'catch' the validation errors to shape the response.

Here's what I have so far.

Register method wrapped in a transaction:

 //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 );
    }

  }

The form request looks like this:

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'
      ];
    }
}

My errors are coming back automatically, which appear to be the messagebag object serialised to JSON

{"email":["The email has already been taken."]}{"email":["The email has already been taken."]}

Somewhere in there I need to catch the Exception inside the main Controller, but I've used the Custom Request Class to clean up my controller a bit, how would I do that? Note the Exception already caught in this controller, which doesn't seem to pickup whatever is thrown behind the scenes in the custom request.

any pointers? do I need to move validation back to the controller? or is there a cleaner way to do this?

1

1 Answers

2
votes

You can override the response method in CreateUserRequest to customize the response:

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