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
CodePudding user response:
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.
- If you were to filter at the application level, all those 100K records have to be sent over the network, and only then you can search.
- With
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.
CodePudding user response:
Performance-wise, it is best practice to use SQL queries for searching data, but this is dependent on your situation.