I have a table named 'categories' with uniqueness constraint on 'category_name' in my application, I want to inset multiple rows in 'categories'.
Bad Solution:
foreach($categories as $category) {
Category::firstOrCreate(array('category_name' => $category['name']));
}
This can be a solution but this is not a good one.The issue is when there will be hunders or thousands of record, this will make a lot of queries to database. which is not good.
Comparativel berter Solution
foreach($categories as $category){
$cats[] = array('category_name' => $category['name']);
}
Category::insert($cats);
But when I try to insert a duplicate 'category_name', it throws an exception and none of category name is inserted.
I know that we can use INSERT IGNORE
but I'm looking for some build in laravel solution.