Aurilie
Aurilie

Reputation: 199

How to ignore duplicates when trying to save data in laravel

I have a categories table and I would like to import all the categories from that table to my new_categories table, I'm using laravel's command to do this for me. The problem is, is that the categories table has duplicate categories and I would like to be able to ignore any duplicates.

So for example my categories table has this

    id | name
    1   | category 1
    2   | category 2
    3   | category 2
    4   | category 2
    5   | category 3

and after I run my code I would like my new_categories table to have this

    id | name
    1   | category 1
    2   | category 2
    3   | category 3

Here is my code

    $old_categories = Category::all();

    $new_categories = DB::table('new_categories')->select('name')->get();

    $newCatArr = [];

    foreach($new_categories as $new_category)
    {
        $newCatArr[] = $new_category->name; 
    }

    foreach($old_categories as $category)
    {
        if(!in_array($category->name, $newCatArr))
        {
            DB::table('new_categories')->insert([
                'name' => $category->name
            ]);
        }
    }

Upvotes: 0

Views: 1995

Answers (1)

vinod
vinod

Reputation: 236

The insertOrIgnore method will ignore duplicate record errors while inserting records into the database:

DB::table('new_categories')->insertOrIgnore([
   'name' => $category->name
]);

For more you can check laravel doc

Upvotes: 1

Related Questions