Michał
Michał

Reputation: 908

Laravel eloquent query running twice

I'm scraping some data from Instagram and then creating a record of it in the database, but sometimes, the record will be inserted twice (or more). When I add an echo in the code it only prints/echos once, so I'm not sure why sometimes the records insert multiple times. Here's the code:

public function handle()
{

    #Define variables
    $website_id = null;
    $user_id = null;
    $avg_dataset_start = null;
    $avg_dataset_end = null;

    try {
        $api = new \Instagram\Api();
        $api->setUserName($this->username);
        $obj = $api->getFeed();

        #quick hack to convert to nested obj
        $data = json_decode(json_encode($obj));

        $data->videos_count = 0;
        $data->pictures_count = 0;
        $data->avgPostLikes = 0;
        $data->avgPostComments = 0;
    } catch (Exception $e) {
        return $e;
    }

    $account = InstagramAccount::where('instagram_id', $data->id)->orWhere('username', $data->userName)->first();

        $scraped_data = InstagramAccountScrape::create([
            'instagram_account_id' => $account->id,
            'username' => $data->userName,
            'full_name' => $data->fullName,
            'biography' => $data->biography,
            'profile_picture_url' => $data->profilePicture,
            'external_url' => $data->externalUrl,
            'website_id' => $website_id,
            'media_count' => $data->mediaCount,
            'followers_count' => $data->followers,
            'following_count' => $data->following,
            'avg_likes_count' => $data->avgPostLikes,
            'avg_comments_count' => $data->avgPostComments,
            'avg_dataset_start' => $avg_dataset_start,
            'avg_dataset_end' => $avg_dataset_end,
            'avg_dataset_photos_count' => $data->pictures_count,
            'avg_dataset_videos_count' => $data->videos_count,
            'is_private' => $data->private,
            'is_verified' => $data->verified,
            'user_id' => $user_id,
        ]); #Sometimes adds more than one record

    echo "Print once please"; #prints once, as expected

    return response()->json($scraped_data); #returns only one instance
}

Upvotes: 2

Views: 1934

Answers (1)

Michał
Michał

Reputation: 908

Figured it out, and it was very strange indeed.

It was caused by a style="background: url('')", where the url was empty, so the browser assumed it was referencing the same page and caused it to load again, sometimes multiple times until the browser decided to stop the reload/load madness.

It happened on all the pages as it was in the layout blade template.

Special thanks to the thread here: MVC controller is being called twice

Upvotes: 2

Related Questions