Refactor Model Creation

Posted 1 year ago by joshgallagher24

I have a block of code that I want to refactor.

Code to refactor:

        $shop = ShopApp::shop();

        if (!$shop->user_id > 0) {
            // Save token to shop
            $shop->shop_token = $api->requestAccessToken(request('code'));

            // External API
            $customerShop = $shop->api()->request('GET', '/shop');

            // Create shop user
            $user = new User;
            $user->name = $customerShop->body->shop->shop_owner;
            $user->email = $customerShop->body->shop->customer_email;
            $user->save();

            // Associate the user with the shop
            $shop->user_id = $user->id;
            $shop->save();

            // Login the shop's user
            Auth::login($user);
        } else {
            $shop->shop_token = $api->requestAccessToken(request('code'));
            $shop->save();

            $user = User::where('id', $shop->user_id)->first();

            Auth::login($user);
        }

The User has a 'has one' relationship to Shop (User has one Shop). I am having problems using things like 'associate' because I need to make an API call to get specific data for the User. Any help would be appreciate!

Please sign in or create an account to participate in this conversation.