Skip to content

Chapter 6 of 7

Queues, Events, Notifications, and Broadcasting

Artisan is Laravel's command-line interface, and a set of common commands covers most daily tasks: serve for the dev server, migrate, make:model, tinker (interactive REPL powered by PsySH), route:list, and cache:clear. Create your own commands with make:command SendEmails, set the $signature property, and put logic in handle(). In Laravel 11+, you can also define single-file closure commands in routes/console.php: Artisan::command('mail:send {user}', fn ($user) => ...)->hourly(). Schedule tasks the same way: Schedule::command('emails:send')->everyMinute()->withoutOverlapping(), then add a cron entry that calls php artisan schedule:run every minute. withoutOverlapping() uses a mutex file to prevent the same task from running concurrently with itself, useful for long-running jobs. Chain ->timezone('Europe/Zagreb'), ->when(fn () => ...), or ->skip() to control when the task fires.

Queues defer slow work (emails, exports, API calls) to a background worker. Generate a job with make:job ProcessPodcast, implement handle(), and dispatch it with ProcessPodcast::dispatch($podcast). Run the worker with php artisan queue:work: it boots the framework once and reuses it across jobs, which is efficient for production. Use queue:listen during development so code changes take effect, since it restarts the framework per job (but is slower). Tune retries with --tries=3, --timeout=60, and --backoff=10; failed jobs land in the failed_jobs table and can be retried with queue:retry all. Configure the driver (Redis, database, SQS) in config/queue.php. For large result sets, combine chunkById with Bus::batch to dispatch many jobs without exhausting memory.

Events decouple triggers from reactions. Generate an event with make:event OrderShipped and a listener with make:listener SendShipmentNotification --event=OrderShipped, then register them in EventServiceProvider (auto-discovery handles most cases). Dispatch with event(new OrderShipped($order)). Event subscribers are classes that subscribe to multiple events from a single subscribe(Dispatcher $events) method, registered in EventServiceProvider::$subscribe. Notifications (which can use the same dispatcher) let a single class deliver to multiple channels such as mail, database, SMS, and Slack. Generate with make:notification InvoicePaid, define channels in via(), and send with \(user->notify(new InvoicePaid(\)invoice)) or Notification::send($users, new InvoicePaid($invoice)). Add 'database' to via() and implement toDatabase() to persist notifications; retrieve with \(user->unreadNotifications and mark with \)notification->markAsRead().

Broadcasting pushes real-time events to WebSocket clients. Implement ShouldBroadcast on an event, define broadcastOn() to return a Channel, PrivateChannel, or PresenceChannel, then trigger the event normally. Front-ends subscribe via Laravel Echo. Authorize private channels in routes/channels.php: Broadcast::channel('orders.{id}', fn ($user, $id) => $user->id === (int) $id). Presence channels additionally return an array of presence data (e.g., user info) used to populate who's online.

All chapters
  1. 1The HTTP Layer: Routing and Middleware
  2. 2Eloquent ORM: Models, Relationships, and Querying
  3. 3Database Migrations, Schema, and Data Seeding
  4. 4Blade Templates, Views, and Pagination
  5. 5Authentication, Authorization, and Sessions
  6. 6Queues, Events, Notifications, and Broadcasting
  7. 7Service Container, Facades, and Cross-Cutting Concerns

Drill it

Reading is not remembering. These come from the Laravel Framework deck:

Q

What is Laravel Eloquent ORM?

Eloquent is Laravel's built-in Active Record ORM. Each database table has a corresponding Model class used to interact with that table. It provides an expressiv...

Q

How do you define a one-to-many relationship in Eloquent?

In the parent model, define a method returning hasMany():public function posts() { return $this->hasMany(Post::class); }In the child model, define the inverse w...

Q

What is eager loading in Eloquent and why is it important?

Eager loading solves the N+1 query problem by loading relationships upfront:$books = Book::with('author')->get();Without it, accessing a relationship in a loop...

Q

How do you create a new Eloquent model and migration together?

Use the Artisan command:php artisan make:model Post -mThe -m flag generates a migration file alongside the model. You can also add -f for a factory and -s for a...