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

Image of Timescale

📊 Benchmarking Databases for Real-Time Analytics Applications

Benchmarking Timescale, Clickhouse, Postgres, MySQL, MongoDB, and DuckDB for real-time analytics. Introducing RTABench 🚀

Read full post →

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

If this article connected with you, consider tapping ❤️ or leaving a brief comment to share your thoughts!

Okay