Sunday, January 22, 2023

Example for laravel cron job which will send 2 birhtday notification mail to user first is one day before and second is the day when birthday is

In your terminal, navigate to the root directory of your Laravel application.

Run the command crontab -e to open the cron tab editor.

Add the following line to the editor: * * * * * php /path/to/your/laravel/installation/artisan schedule:run >> /dev/null 2>&1

Save and exit the editor.

This will run the Laravel task scheduler every minute.


Next, you can define two new tasks in your app/Console/Kernel.php file that will send birthday notifications to users.


use App\User;

use Carbon\Carbon;

use Illuminate\Console\Scheduling\Schedule;

use Illuminate\Support\Facades\Mail;


class Kernel extends ConsoleKernel

{

    protected function schedule(Schedule $schedule)

    {

        $schedule->call(function () {

            $users = User::all();

            foreach ($users as $user) {

                if($user->birthday->isToday()) {

                    Mail::to($user->email)->send(new BirthdayEmail($user));

                }

                if($user->birthday->isTomorrow()) {

                    Mail::to($user->email)->send(new BirthdayReminderEmail($user));

                }

            }

        })->daily();

    }

}

In model: 

use Carbon\Carbon;


class User extends Authenticatable

{

    // other model properties and methods


    public function isToday()

    {

        return Carbon::today()->isSameDay($this->birthday);

    }

   public function isTomorrow()

    {

        return Carbon::tomorrow()->isSameDay($this->birthday);

    }

    public function isTwoDaysBefore()

    {

        return Carbon::now()->addDays(2)->isSameDay($this->birthday);

    }

}

 

No comments:

Post a Comment