psudo
psudo

Reputation: 1578

Insert only unique values into db table

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.

Upvotes: 1

Views: 4314

Answers (2)

Johnathan Barrett
Johnathan Barrett

Reputation: 556

...
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();
        }               
    }
}

Upvotes: 2

nakov
nakov

Reputation: 14318

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]);
}

Upvotes: 5

Related Questions