Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

dzalev's avatar

Help with sending emails Query

Hey all i need some help with a query for sending emails. I have a field in my users table 'last_login' in witch i am storing the date and time when the user was last logged in. i need to check if the user is not logged in for more than 2 days and send them an email reminder. any thoughts on how to do this? is there any Laravel helper for this kinds of scenarios?

0 likes
7 replies
tisuchi's avatar

Maybe you can use a job for that. The job will call once every hour. The responsibilities of the job are-

  • Fetch user data where last_login is more than 2 days from now
  • Trigger email.
2 likes
dzalev's avatar

you mean like setting up a cron job and triger a command ?

rodrigo.pedra's avatar
Level 56

You'll need a scheduled job to check this for you, or - if you cannot configure scheduled jobs - you'll need to trigger this check manually.

Create a Command:

php artisan make:command NotifyStaleUsers --command=app:notify-stale-users

On the generated NotifyStaleUsers class add this code to its handle method:

User::query()
    ->where('last_login', '<', now()->subDays(2)->startOfDay())
    ->each(function (User $user) {
        // send e-mail
        Mail::to($user)->send(new StaleUserEmail());
    });

You'll need to create a mailable named StaleUserEmail to this code work. Please refer to the documentation on how to create this mailable:

https://laravel.com/docs/6.x/mail#writing-mailables

After that add a scheduled task to your app/Console/Kernel.php file:

protected function schedule(Schedule $schedule)
{
    $schedule->command('app:notify-stale-users')->dailyAt('00:01');
}

Again, you'll need to configure your app scheduler, please refer to the documentation on how to do this:

https://laravel.com/docs/6.x/scheduling

If you cannot, for some reason, configure the scheduler, one option is to create a route that call this command and call it manually or from a scheduled task in your OS (Windows, Linux, etc.)

// routes/web.php

use \Illuminate\Support\Facades\Route;
use \Illuminate\Support\Facades\Artisan;

Route::get('/stale-users', function () {
    Artisan::call('app:notify-stale-users');
});

This is a simplified example, if you take this approach please add some authentication mechanism over this route.

dzalev's avatar

Thanks for the detailed example! it worked with minor changes

1 like
rodrigo.pedra's avatar

Great! Glad to help.

Is this minors changes are more than adaptions to your case and could help others please post it here too for reference :)

1 like
dzalev's avatar

Only some specific project details noting more, Thank you very much

Please or to participate in this conversation.