DEV Community

Ankit Verma
Ankit Verma

Posted on

Dispatching jobs via commands in Laravel

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

Top comments (0)