Monday, October 5, 2020

Laravel send email to in active users using cron job

 Hi Artisan

In this tutorial i will explain about laravel task scheduling. I will show you step by step about laravel custom cron schedule. In this tutorial, i would like to show you how to setup task scheduling cron job in laravel 7 application.

In this tutorial we will first find out our inactive user and send them email notification to their email address using laravel custom command. We will send this notification using laravel task scheduling.

If you still don't know what is task scheduling and how to use it, then you are a right place. Task scheduling is a system where you can run a method after a couple of minute, second or hour.

we will create laravel custom cron schedule and you can run cron every seconds, every minutes, every hours or every days. you can also write database logic or send email notification using laravel cron job. i will give step by step example of laravel 7 task scheduler tutorial.

In this tutorial we will see how we can create our laravel custom command and using this command and using task scheduling with cron job, how we can send notification to our inactive user from our application.

laravel-task-scheduling-example-with-cron-job

Task Scheduling Example In Laravel

So for making it we have to add a new field in our user database table, So let's add a new field to our user database table. 

Step 1: Setup Table

Now go to user table and paste this below code to your user table.

   Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->string('role')->default('user');
            $table->tinyInteger('active')->default(1);
            $table->timestamp('last_login')->nullable();
            $table->rememberToken();
            $table->timestamps();
        });
PHP

 

Now after adding it run migrate command to add this field.  See here we add last_login field to check when was the user last logged in.

Step 2: Create Custom Command

For creating our custom command , run this below command

php artisan make:command ourCustomCommandName 
php artisan make:command inactive-users
PHP

 

After running this command you will see this file to this following directory app\Console\Commands\EmailInactiveUsers.php.

 

Step 3: Setup EmailInactiveUsers.php

Open app\Console\Commands\EmailInactiveUsers.php and paste the following code.

 

Read more : Binding Data to Views Using View Composers in Laravel

app\Console\Commands\EmailInactiveUsers.php

namespace App\Console\Commands;

use App\Notifications\NotifyInactiveUser;
use Carbon\Carbon;
use Illuminate\Console\Command;

class EmailInactiveUsers extends Command
{

    protected $signature = 'command:name';

    protected $description = 'command description';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        //Logic goes here

    }
}
PHP

 

Now see protected $signature = 'command:name'; this should be our custom command name  and In handle() method , we have to setup our logic.

 

Step 4: Make Notification

Run this command to make new notification

php artisan make:notification NotifyInactiveUser
PHP

 

After running this command you will see this file to this following directory app\Notifications\NotifyInactiveUser.php and paste this below code

app\Notifications\NotifyInactiveUser.php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;

class NotifyInactiveUser extends Notification
{
    use Queueable;

    public function __construct()
    {
        //
    }

    public function via($notifiable)
    {
        return ['mail'];
    }

    public function toMail($notifiable)
    {
        return (new MailMessage)
            ->line('You are not using our website for a long time')
            ->action('Please login again', route('login'))
            ->line('Thank you for joining our codechief community!');
    }

    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}
PHP

 

Step 5: Setup EmailInactiveUsers.php

Open app\Console\Commands\EmailInactiveUsers.php and paste the following code.

namespace App\Console\Commands;

use App\Notifications\NotifyInactiveUser;
use Carbon\Carbon;
use Illuminate\Console\Command;

class EmailInactiveUsers extends Command
{

    protected $signature = 'email:inactive-users';

    protected $description = 'Email inactive users';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $limit = Carbon::now()->subDay(7);
        $inactive_user = User::where('last_login', '<', $limit)->get();

        foreach ($inactive_user as $user) {
            $user->notify(new NotifyInactiveUser());
        }
    }
}
PHP

 

Now if you run php artisan then you we see our custom command in laravel artisan command list.

task-scheduling-with-cron-job-in-laravel-58example

 

Here we use this $limit = Carbon::now()->subDay(7); statement to get who logged in 7 days before and then send them notification.

 

Step 6: Setup Auth Controller

To save last_login field data, go to your login mechanism and paste this below code to your login attempt method.

$user = auth()->user();
$user->last_login = Carbon::now();
$user->save();
PHP

 

See here we've saved current time when a user is going to log in.

Setup Task Scheduling

Step 7: Register Our Custom Command class and Scheduler

 

To register our custom command , go to app\Console\Kernel.php. In Kernel.php , register our command class inside $commands array.

app\Console\Kernel.php

EmailInactiveUsers::class,
PHP

 

and paste this code to control schedule.

 $schedule->command('email:inactive-users')
            ->weekly();
PHP

 

Look in schedule method, we can define how many time later we want to process our schedule. To know more you can visit below links.

 

https://laravel.com/docs/5.8/scheduling

 

So our ultimate Kernel.php will look like this

namespace App\Console;

use App\Console\Commands\EmailInactiveUsers;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{

    protected $commands = [
        EmailInactiveUsers::class,
    ];

    protected function schedule(Schedule $schedule)
    {
        $schedule->command('email:inactive-users')
            ->weekly();
    }

    protected function commands()
    {
        $this->load(__DIR__ . '/Commands');

        require base_path('routes/console.php');
    }
}
PHP

 

Now if you run 

php artisan email:inactive-users
PHP

 

Then our logic will work. That mean our notification will be sent to those user who logged in 7 days ago. hope you got it.

 

Step 8: Run Scheduler Command For Test

now we are ready to run our cron, so you can manually check using following command of your cron. so let's run bellow command:

php artisan schedule:run
PHP

 

At last you can manage this command on scheduling task, you have to add a single entry to your server’s crontab file:

* * * * * php /path/to/artisan schedule:run 1>> /dev/null 2>&1
OR
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
PHP

 

I hope it can help you.


https://www.codechief.org/article/send-notification-to-inactive-user-with-task-scheduling-in-laravel-using-custom-command