Jivan Bhandari
Jivan Bhandari

Reputation: 860

Laravel loop through all data in database through schedule command

I am looking for an efficient way to loop through all the records of all users, check for a condition and if the condition is met I need to send an email.

This task is to be done daily at some specified time. So a cron job will be running in the background.

Right now I am populating all the records for the database and using for loop to check the condition. This is working fine for now. But I don't think this is the best solution when data start growing.

Any idea on using limit to get whole database data?

Upvotes: 0

Views: 2035

Answers (2)

Milan Tarami
Milan Tarami

Reputation: 80

The solution is laravel queue . You can check all the data and if the condition match dispatch and delay the send mail process to queue. Tutorial 1

Upvotes: 0

lovis91
lovis91

Reputation: 2171

If you have a lot of records, use chunk : https://laravel.com/docs/5.7/queries#chunking-results

DB::table('users')->orderBy('id')->chunk(100, function ($users) {
    foreach ($users as $user) {
        //
    }
});

Upvotes: 3

Related Questions