1

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 Answer 1

2

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

public function response(array $errors)
{
    return parent::response($errors);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Yeah, that looks like it will do it, I've just var_dumped $errors.. any idea why I may have two errors in the JSON?
Only duplicate email? Sends the request without another field required as a name

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.