'Laravel Complex API Code Optimization to avoid nested loops

Introduction

Hi, I hope everyone is doing great. I am a little advance to beginner level in Laravel and developing a system where I have to use Instagram API to get all the data against different hashtags.

These hashtags could be 1, or 2, or even more. Here is the code that I am sharing, this code is taking too much time to run because of the nested loops in it. Can anyone who is expert share his/her knowledge and give me suggestions on how to improve this piece of code?

The code

   public function getHastagMediaByID($token)
{
    $client = new \GuzzleHttp\Client();
    $event_hashtag = $this->event->hashtag;
    $hashtagArray = explode(',', $event_hashtag);
    $hashtagIdArray = array();
    // dd($hashtagArray);
    $count = 0;
    $decodedInstagramDataApiResponse = null;
    if (isset($hashtagArray)) {
        $userIGAccounts = Event_Social_Post::where('event_id', $this->event->id)->where('platform', 'instagram')->get();
        if ($userIGAccounts != null) {
            foreach ($userIGAccounts as $userinstaAcc) {
                try {
                    $userInstaAccId = $userinstaAcc->page_id;
                    $instagramUserDataApi = $client->request('GET', "https://graph.facebook.com/v12.0/$userInstaAccId?fields=username%2Cprofile_picture_url&access_token=$token");
                    $getInstagramDataApiResponse  = $instagramUserDataApi->getBody()->getContents();
                    $decodedInstagramDataApiResponse[] = json_decode($getInstagramDataApiResponse, true);
                    foreach ($hashtagArray as $key => $hashtagValue) {
                        if (isset($hashtagValue) && $hashtagValue != "") {
                            try {
                                $hashtagValue = ltrim($hashtagValue);
                                $InstagramHashtagIdApi = $client->request('GET', "https://graph.facebook.com/v11.0/ig_hashtag_search?user_id=$userInstaAccId&q=$hashtagValue&access_token=$token");
                                $getInstagramHashTagApiResponse = $InstagramHashtagIdApi->getBody()->getContents();
                                $decodedInstagramHashTag = json_decode($getInstagramHashTagApiResponse, true);
                                $InstagramHashtagID = $decodedInstagramHashTag['data'][0]['id'];
                                $hashtagPostSearchApi = $client->request('GET', "https://graph.facebook.com/v11.0/$InstagramHashtagID/recent_media?user_id=$userInstaAccId&fields=id%2Crecent_type%2Ccomments_count%2Clike_count%2Ccaption%2Cmedia_url%2Cpermalink%2Cchildren{media_url}%2Ctimestamp&access_token=$token");
                                $getHashtagPostSearchApiApiResponse = $hashtagPostSearchApi->getBody()->getContents();
                                $decodedHashtagPostSearchResponse = json_decode($getHashtagPostSearchApiApiResponse, true);
                                $hashtagIdArray[] = $decodedHashtagPostSearchResponse;
                                //   var_dump($hashtagIdArray);
                                $count++;
                            } catch (ClientException $e) {
                                $response = $e->getResponse();
                                $responseBodyAsString = $response->getBody()->getContents();
                                if (Auth::check()) {
                                    Session::put('instagramException', 'true');
                                    Session::put('instagramExceptionMessage', $responseBodyAsString);
                                }
                                continue;
                            }
                        }
                    }
                } catch (ClientException $e) {
                    $response = $e->getResponse();
                    $responseBodyAsString = $response->getBody()->getContents();
                    if (Auth::check()) {
                        Session::put('instagramException', 'true');
                        Session::put('instagramExceptionMessage', $responseBodyAsString);
                    }
                    continue;
                }
            }

            if (count($hashtagIdArray) > 0) {
                foreach ($hashtagIdArray as $key => $post) {
                    $userDataLoopIndex = 0;
                    if (count($post['data']) > 0) {
                        // dd($post['data']);
                        foreach ($post['data'] as $postDatum) {
                            if (isset($postDatum['children'])) {
                                foreach ($postDatum['children'] as $key => $childrenData) {
                                    foreach ($childrenData as $childrenSingleton) {
                                        // $childrenSingleton['media_url'];
                                        $soc = new E_social_wall;
                                        $soc->text = $postDatum['caption'] ?? ''; //->caption;
                                        $soc->image = $childrenSingleton['media_url'] ?? ''; //->media_url;
                                        $soc->platform = 'instagram';
                                        if ($userDataLoopIndex < count($decodedInstagramDataApiResponse)) {
                                            //dd($media['userData']);
                                            if (isset($decodedInstagramDataApiResponse[$userDataLoopIndex]['profile_picture_url'])) {
                                                $soc->user_img = $decodedInstagramDataApiResponse[$userDataLoopIndex]['profile_picture_url'];
                                            } else {
                                                $soc->user_img = 'https://www.kindpng.com/picc/m/22-223930_avatar-person-neutral-man-blank-face-buddy-facebook.png';
                                            }
                                            $soc->username = $decodedInstagramDataApiResponse[$userDataLoopIndex]['username'] ?? 'anonymous';
                                            $userDataLoopIndex++;
                                        } else if ($userDataLoopIndex >= count($decodedInstagramDataApiResponse)) {
                                            $userDataLoopIndex = 0;
                                            if (isset($decodedInstagramDataApiResponse[$userDataLoopIndex]['profile_picture_url'])) {
                                                $soc->user_img = $decodedInstagramDataApiResponse[$userDataLoopIndex]['profile_picture_url'];
                                            } else {
                                                $soc->user_img = 'https://www.kindpng.com/picc/m/22-223930_avatar-person-neutral-man-blank-face-buddy-facebook.png';
                                            }

                                            $soc->username = $decodedInstagramDataApiResponse[$userDataLoopIndex]['username'] ?? 'anonymous';
                                            $userDataLoopIndex++;
                                        }

                                        $soc->posted_at = date('Y-m-d h:i', strtotime($postDatum['timestamp']));
                                        $soc->url = $childrenSingleton['media_url'] ?? ''; //->media_url;
                                        $soc->event_id = $this->event->id;
                                        $soc->is_hashtag = 1;
                                        if ($soc->image != '' ||   $soc->url != '') {
                                            $soc->save();
                                        }
                                        $count++;
                                    }
                                }
                            } else {
                                $soc = new E_social_wall;
                                $soc->text = $postDatum['caption'] ?? ''; //->caption;
                                $soc->image = $postDatum['media_url'] ?? ''; //->media_url;
                                $soc->platform = 'instagram';
                                if ($userDataLoopIndex < count($decodedInstagramDataApiResponse)) {
                                    //dd($media['userData']);
                                    if (isset($decodedInstagramDataApiResponse[$userDataLoopIndex]['profile_picture_url'])) {
                                        $soc->user_img = $decodedInstagramDataApiResponse[$userDataLoopIndex]['profile_picture_url'];
                                    } else {
                                        $soc->user_img = 'https://www.kindpng.com/picc/m/22-223930_avatar-person-neutral-man-blank-face-buddy-facebook.png';
                                    }
                                    $soc->username = $decodedInstagramDataApiResponse[$userDataLoopIndex]['username'] ?? 'anonymous';
                                    $userDataLoopIndex++;
                                } else if ($userDataLoopIndex >= count($decodedInstagramDataApiResponse)) {
                                    $userDataLoopIndex = 0;
                                    if (isset($decodedInstagramDataApiResponse[$userDataLoopIndex]['profile_picture_url'])) {
                                        $soc->user_img = $decodedInstagramDataApiResponse[$userDataLoopIndex]['profile_picture_url'];
                                    } else {
                                        $soc->user_img = 'https://www.kindpng.com/picc/m/22-223930_avatar-person-neutral-man-blank-face-buddy-facebook.png';
                                    }

                                    $soc->username = $decodedInstagramDataApiResponse[$userDataLoopIndex]['username'] ?? 'anonymous';
                                    $userDataLoopIndex++;
                                }

          $soc->posted_at = date('Y-m-d h:i', strtotime($postDatum['timestamp']));
                                $soc->url = $postDatum['media_url'] ?? ''; //->media_url;
                                $soc->event_id = $this->event->id;
                                $soc->is_hashtag = 1;
                                if ($soc->image != '' ||   $soc->url != '') {
                                    $soc->save();
                                }
                                $count++;
                            }
                        }
                    }
                }
            }


            return array('response' => $hashtagIdArray, 'userData' => $decodedInstagramDataApiResponse);
        }
    }
}

any suggestion or help would be great. Thank you all in advance.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source