mercredi 4 novembre 2015

Unable to get Auth::user()->id

I have two controllers; AuthController and CheckoutController now my AuthController handles User Logins and Registrations, when the user logins i am able to check their logged in status and get their user_id from the AuthController.

However when i try to do this in my CheckoutController i always have Auth::user()->id returning this error:

Trying to get property of non-object

.

No matter what i do it's always the same, i have looked online for solutions but haven't found anything about this.

I just realized something though, my AuthController and CheckoutController are in 2 different namespaces and i am wondering if this could be the cause/reason.

This is my login code:

/**
     * Handle a login request to the application.
     *
     * @param  LoginRequest  $request`
     * @return Response
     */
    public function postLogin(LoginRequest $request)
    {
        $credentials = $request->only('email', 'password');

        try {
            // verify the credentials and create a token for the user
            if (!$token = JWTAuth::attempt($credentials)) {
                return response()->json(['code' => 300, 'message' => 'invalid_credentials'], 401);
            }
        } catch (JWTException $e) {
            // something went wrong
            return response()->json(['error' => 'could_not_create_token'], 500);
        }

        $url_parts = parse_url($request->url());
        $host_parts = explode('.', $url_parts['host']);

        if ($host_parts[0] == "admin")
        {
            $user = User::find(Auth::user()->id);
            if (!$user->is('administrator'))
            {
                Auth::logout();
                return response()->json(['error' => 'You Are Not Authorized!']);
            }
        }

        // if no errors are encountered we can return a JWT
        return response()->json(compact('token'));
    }



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire