How to write a return response for if the user already exists in Laravel?

Viewed 536

I developed an API, and it's returning a response when the user is registered successfully as 201. If the user is already registered (based on emailID), I want to return a response as 422. How can I do that?

UserController.php

class UserController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:api', ['except' => ['login', 'register']]);
    }

    public function register(Request $request)
    {
        $this->validate($request, [
            'fullName' => 'required|string|between:3,15',
            'emailID' => 'required|email|unique:users',
            'password' => 'required|regex:/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{6,}$/',
            'mobile' => 'required|digits:10'
        ]);

        $user = new User([
            'fullName' => $request->input('fullName'),
            'emailID' => $request->input('emailID'),
            'password' => bcrypt($request->input('password')),
            'mobile' => $request->input('mobile')
        ]);

        $user->save();

        return response()->json(['message' => 'Successfully Created user'], 201);

        // I am trying follow if condition it's not working
        if ($request->fails()) {
            return response()->json(['message' => "already exits"], 422);
        }
    }
}
1 Answers

Model::save() returns a boolean that you might use. Alternatively, you can use Model::saveOrFail() that throws an exception if it can't insert. Another way to determine if the model already exists, is the $exists property but that might not have been set yet (haven't tested it).

$user = new User([
    'fullName' => $request->input('fullName'),
    'emailID' => $request->input('emailID'),
    'password' => bcrypt($request->input('password')),
    'mobile' => $request->input('mobile')
]);

$successfull = $user->save();

if (!$successfull) {
    return response()->json(['message' => "already exits"], 422);
}

return response()->json(['message' => 'Successfully Created user'], 201);
Related