1

I'm using vinkla/instagram composer package in my Laravel to fetch Instagram posts in my app.

Since Instagram allows the package to call their API 200 times per hour I'm trying to save post links into database table. And this package fetches 20 latest posts and its attributes.

Here I'm trying to compare the link of posts fetched by vinkla/instagram composer package and already saved posts and insert only unique into to table. Below is the code snippet:

    $instagram = new Instagram('access-token');
    $posts = $instagram->media(); //gets 20 latest insta posts of a user
    $fromDBs = Insta::orderBy('id', 'desc')->take(20)->get(); //get last 20 rows from table
    foreach( $posts as $post)
    {
        foreach( $fromDBs as $fromDB)
        {
            if($post->images->low_resolution->url != $fromDB->link)
            {
                $create = new Insta;
                $create->link =  $post->images->low_resolution->url;
                $create->save();
            }               
        }
    }

With the above stated code the new links are inserted x10 times. What would be the correct way to insert unique link once only.

2 Answers 2

5

There are firstOrCreate or firstOrNew helper functions on eloquent, so you can create it only if it does not exist in order to prevent duplicates. So instead of your check you can check this code:

foreach( $posts as $post)
{
    Insta::firstOrCreate(['link' => $post->images->low_resolution->url]);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Laravel beauty.
2
...
foreach( $posts as $post)
{
    foreach( $fromDBs as $fromDB)
    {
        if($post->images->low_resolution->url != $fromDB->link)
        {
            $create = Insta::firstOrNew(['link' => $post->images->low_resolution->url]);

           if(! $create->id ) $create->save();
        }               
    }
}

1 Comment

@nakov's solution is better

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.