Laravel event and listeners example; In this tutorial you will learn how to use, work and implement Events and Listeners in laravel application.
Laravel provides an excellent way to hook into a certain event in your application using Events and Listeners. This feature will allow you to subscribe and listen to various activities that took place in your application. As a result, Events and Listeners will further help to simplify our codes and refactor complicated tasks. You can use sending email varification or login, logout event with listener in laravel as well.
Here in this example when a post created, the users will be notified about the post through emails. Many times we need to notify the users or something else for laravel event and listeners use. Sending an email or login or logout events with listeners are usefull to work with admin panel in laravel.
Laravel Event & Listeners Example Steps
Use to follow the following steps to integrate and implement event and listeners in laravel 9 | 8 apps.
Step 1: Create Event
First at all, you need to create an event in laravel using the following artisan command:
php artisan make:event PostCreated
This event is created in your app/Events path. Now open your app\Events\PostCreated.php and put the below code on it;
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
use App\Post;
class PostCreated
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $post;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct(Post $post)
{
$this->post = $post;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('channel-name');
}
}
Step 2: Create Listener
Now you need to create a listener NotifyPostCreated using the following commands:
php artisan make:listener NotifyPostCreated --event="PostCreated"
The listener path is app/Listeners where the new file notify post crated just like below:
So open app\Listeners\NotifyPostCreated.php file and put the below code on it;
<?php
namespace App\Listeners;
use App\Events\PostCreated;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use App\Events\PostCreated;
use App\User;
use Mail;
class NotifyPostCreated
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param PostCreated $event
* @return void
*/
public function handle(PostCreated $event)
{
$users = User::all();
foreach($users as $user) {
Mail::to($user)->send('emails.post_created', $event->post);
}
}
}
Step 3: Register Event to Providers
Now we register our event and listener in app/Providers/EventServiceProvider.php file with the following code:
<?php
namespace App\Providers;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;
use App\Events\PostCreated;
use App\Listeners\NotifyPostCreated;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
],
PostCreated::class => [
NotifyPostCreated::class,
],
];
/**
* Register any events for your application.
*
* @return void
*/
public function boot()
{
//
}
}
Step 4: Dispatch Event From Controller in Laravel
In this step we trigger or fire the PostCreated event. All you need to do is use event() helper. This helper will dispatch the event to all of its registered listeners.
<?php
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'description' => 'required',
]);
$post = Post::create($request->all());
event(new PostCreated($post)); // dispatch event from here
//You can use the below commented code
//PostCreated::dispatch($post);
return redirect()->route('posts.index')->with('success','Post created successfully.');
}
}
Step 5: Create Email Template
Go to resources/views folder and create a folder named emails. Under emails folder create a file called post_created.blade.php. Then open file and paste this code:
resources\views\emails\post_created.blade.php
<html>
<head>
</head>
<body>
<div class="containter">
Hi {{ $user['name'] }},<br><br>
A new post created right now checkout here.<a href="https://codingdriver.com/">Coding Driver</a><br>
</div>
</body>
</html>
That’s all the event and listener in laravel tutorial with example is over now. I hope you enjoy with this article, feel free to contact us and share to your artisans friends as well.
1 thought on “Laravel 9 Events and Listeners Tutorial with Example”