lundi 29 février 2016

Refactor Laravel Controller to send response from another method

I have two methods in same controller. In first half of both these methods I am creating user,and sending error response if there is some validation issue. I am able to refactor that repeating code into createUserFromRequest.

 public function createUserFromRequest(Request $request)
    {
        $user = $this->getUserFromRequest($request);
        $userRepo = new UserRepository($user);
        if($userRepo->userExists())
        {
            return response()->json(['toast'=>$this->responseOnFailure()]);
        }
        if(!$userRepo->saveUser())
        {
            return response()->json(['toast'=>$this->responseOnFailure()]);
        }
        return $user;
    }
protected function getUserFromRequest(Request $request)
{
    $user = new User;
    $user->email = $request->email;
    $user->first_name = $request->first_name;
    $user->last_name = $request->last_name;
    $user->password = \Hash::make($request->password);
    return $user;
}

I am not able to use it, since in case of error it is returning response()->json(). So what is the way I can send response from other method in case of error and process normally in case there isn't any.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire