1
votes

I'm using Lumen with Dingo API for building an API. My registration function checks to see if the email specified already exists.

Using Dingo API Helpers to return an error response if the email already exists in the database.

Dingo\Api\Routing\Helpers

isEmailTaken function:

private function isEmailtaken($email) {
    $userExists = User::where('email', $email)->count();
    if($userExists) {
        $return['error'] = true;
        $return['message'] = "It appears you already have an account with us.";
        return $return;
    } else {
        $return['error'] = false;
        return $return;
    }
}

The registration function calls that function and returns an error:

    $validateEmail = $this->isEmailtaken($email);
    if ($validateEmail['error'] == true) {
        return $this->response->errorBadRequest($validateEmail['message']);
    }

It outputs the correct error message with the correct error code in the json response:

"{"message":"It appears you already have an account with us.","status_code":400}"

However, the status generated by the response in the header is OK and code is 200.

1

1 Answers

0
votes

status_code 400 bad request will return when the request data is not valid

below code help to return the response with custom status_code

use Illuminate\Http\Response; 


return response()->json(['message' => 'It appears you already have an account with us.'])->setStatusCode(400);

Also the shorted way to validate unique emailID from the laravel validation like below

 $rules = array(

            'email'=>'required|email|unique:user',
            );  

    $validator = Validator::make($request->all(), $rules);

    if (!$validator->passes()) {  
        return response()->json([ 'message' => $validator->messages()])->setStatusCode(400);

}