How to use Events and Listeners in Laravel?


Posted 3 months ago | by Ryan Dhungel | on Laravel  | Viewed 298 times

An example of using Events and Listeners in laravel.

For example while creating a blog, you might want to email the users, subscribe them or add the blog to search index etc.

Instead of doing everything inside single controller method, we can create seperate Events and Listeners for each of those actions:

Create a new blog and use artisan command to create a new event called BlogWasCreated.

art make:event BlogWasCreated

BlogController.php

use App\Events\BlogWasCreated;

public function create()
    {
        $blog = new Blog;
        $blog->title = 'New Blog';
        // fire an event
        event(new BlogWasCreated($blog));
        // email
        // subscribe
        // search index
        $blog->save();
    }

BlogWasCreated.php

use App\Blog;

class BlogWasCreated

public $blog;

    public function __construct(Blog $blog)
    {
        $this->blog = $blog;
    }

Terminal

art make:listener EmailUserAboutCreatedBlog --event=BlogWasCreated

Listeners/EmailUserAboutCreatedBlog.php

public function handle(BlogWasCreated $event)
{
var_dump('email user');
}

Define Event and Listeners relationships

Providers/EventServiceProviders.php

protected $listen = [
'App\Events\BlogWasCreated' => [
'App\Listeners\EmailUserAboutCreatedBlog',
// go through the same process to add more events here
],
];

These are the key steps of using Events and Listeners in Laravel.



Specials


Build Laravel React CRUD/SPA APP in 2 hours
Build Laravel React CRUD/SPA APP in 2 hours

Build Laravel React CRUD/SPA APP in 2 hours

COUPON CODE: REACTCRUD with 90% off


Laravel with React JS - Build Twitter Like Real Ti...
Laravel with React JS - Build Twitter Like Real Time Web App

Laravel with React JS - Build Twitter Like Real Time Web App

COUPON CODE: LARAVELREACT with 90% off


Learn Laravel Building Multi User Blogging Platfor...
Learn Laravel Building Multi User Blogging Platform with SEO


React Redux Firebase CRUD App with Authentication
React Redux Firebase CRUD App with Authentication

React Redux Firebase CRUD App with Authentication

COUPON CODE: RRFTEN with 86% off


Become a Master of JavaScript from Scratch in 2018
Become a Master of JavaScript from Scratch in 2018

Become a Master of JavaScript from Scratch in 2018

COUPON CODE: JSMASTERSALE with 92% off


REACT - Up and Running with React ES6 and Open Sou...
REACT - Up and Running with React ES6 and Open Source API


Sublime Text for Rapid Web Development
Sublime Text for Rapid Web Development

Sublime Text for Rapid Web Development

COUPON CODE: LEARNSUBLIME with 90% off