Dispatching jobs via commands in Laravel
Ankit Verma

Ankit Verma @ankitvermaonline

About: Full Stack Developer 7+ years of experience in Web development, specializing in PHP frameworks.

Location:
Lucknow
Joined:
Sep 18, 2023

Dispatching jobs via commands in Laravel

Publish Date: Mar 24
0 0

Make a job

php artisan make:job SendBirthdayWishes
Enter fullscreen mode Exit fullscreen mode

Modify app/Jobs/SendBirthdayWishes.php to send birthday wishes.

namespace App\Jobs;

use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;

class SendBirthdayWishes implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        $today = now()->format('m-d'); // Get today's month and day

        // Get users whose birthday is today
        $users = User::whereRaw("DATE_FORMAT(birthday, '%m-%d') = ?", [$today])->get();

        foreach ($users as $user) {
            Log::info("Happy Birthday {$user->name}!");

            // You can also send an email
            // Mail::to($user->email)->send(new HappyBirthdayMail($user));
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Dispatch the Job Using Tinker

php artisan tinker
Enter fullscreen mode Exit fullscreen mode
dispatch(new App\Jobs\SendBirthdayWishes)
Enter fullscreen mode Exit fullscreen mode

Comments 0 total

    Add comment