Search code examples
laravellaravel-passport

How can I HTTP request to the same server for access token?


While I want to get access token after request, I run into a deadlock situation. There is no problem in the user create section. When I look after deadlock to my database, the new user was written here. After the deadlock, I must clean my cache and restart server, otherwise, the project will not run. What can I do?

Controller:

public function first_step_register(FirstRegisterRequest $request){

    try {
        $user = User::firstOrCreate([
            'name' => $request->name,
            'email' => $request->email,
            'surname' => $request->surname,
            'phone' => $request->phone,
            'role_id' => $request->role,
            'password' => Hash::make($request->password),
        ]);
        if ($user){

            $http = new Client();

            $response = $http->post(route('passport.token'), [
                'form_params' => [
                    'grant_type' => 'password',
                    'client_id' => '2',
                    'client_secret' => 'T8X7xNsgmw7LEqkGDwk1PhVnWO2NepqT7y48SodE',
                    'username' => $request->email,
                    'password' => $request->password,
                    'scope' => '',
                ],
            ]);

            return response([
                'data' => new FirstRegisterResource($user),
                'token' => json_decode((string) $response->getBody(), true),
            ], Response::HTTP_CREATED);
        }
        else{
            return response([
                'error' => 'Something went wrong, not created'
            ], Response::HTTP_NOT_IMPLEMENTED);
        }
    } catch (\Exception $e) {
        report($e);
        return response([
            'error' => $e
        ],Response::HTTP_NOT_IMPLEMENTED);
    }
}

Solution

  •  public function login(LoginRequest $request){
        try{
            $user = User::where('email', $request->email)->first();
            if ($user){
                if(Hash::check($request->password, $user->password)){
                    return response([
                        'data' => new EmailVerificationResource($user)
                    ],Response::HTTP_ACCEPTED);
                }
                else {
                    return response([
                        'error' => 'These password does not match with email.'
                    ],Response::HTTP_NOT_ACCEPTABLE);
                }
            }else{
                return response([
                    'error' => 'These email does not match our records.'
                ],Response::HTTP_NOT_ACCEPTABLE);
            }
        }
        catch (\Exception $e){
            report($e);
            return response([
                'error' => $e
            ],Response::HTTP_UNAVAILABLE_FOR_LEGAL_REASONS);
        }
    }