My question is relevant to the concept of searching data. I am developing a project with Laravel.
The question is, which is efficient? Get data from the database and search through PHP, Or prepare the SQL command and search inside the database.
Description:
if want to explain more, I face with this two types of coding:
$result = Model::where()->with()->...->paginate();
The other way:
$result = Model::all();
$result->filter(function ($items) use ($search) {
return ...;
});
Of course, these codes were simple.
Thanks
2
Answers
Performance-wise, it is best practice to use SQL queries for searching data, but this is dependent on your situation.
It would help how you are measuring efficiency – quicker to write, easier to comprehend, faster to run, etc.
I would choose execution inside the database all the time when I can.
Imagine you are going to search through 100K records.
WHERE
clauses, the number of records will be very small and go easy on the network. This is because the filter will be applied in place.That being said, I have been in situations where I couldn’t filter at the DB level and had to filter at the application level. They were extremely slow, needless to say.