How best to do the checking of entries in the array unique?

Generally there is an array of 10 records, the table has 10000 records. You need to determine which records in the array is not in the table and then insert. Before that I was so
$select_all_news = DB::select("select * from news WHERE author='author'");

That is essentially pulled the floor of the table, and then have two for loops and foreach replayed, comparing arrays. Thus was formed an array of unique news. (one request to database)

now fix it
for ($x=0; $x<count($all_news['url']); $x++)

In this case, 10 queries, as there is a reconciliation it is for each record.

Which option is more correct and why?
March 19th 20 at 09:00
2 answers
March 19th 20 at 09:02
The second option has a right to exist. Additionally, I would advise you to add indexes to a combination of the fields "source" and "author" to speed up the search. And not to do ->first() to check the existence of records, this is the exists method.
Can a concrete example about the indexes for my version? (don't know what it is) - sean commented on March 19th 20 at 09:05
@sean, this information is easy to Google. Here is the link to the docks of laravale, there are examples of how to create indexes in the migration: - Antonio commented on March 19th 20 at 09:08
March 19th 20 at 09:04
Queries in loops is very bad, it is always advisable to get rid of it.
You have to be a unique key in the database, so no dubbing. When you do, you can use insert ignore
Your code can be simplified, using the method firstOrCreate

To get rid of queries in a loop you need
1. To make a request to the database whereIn
2. A walk cycle that was found and filter
3. Remaining to add a single insert
Thus you will have only two requests

Find more questions by tags Laravel