Premium Courses

Learn practical web development building multi user SEO blog app in Laravel. A Journey from localhost to live server.

Learn the fastest growing and high in demand React Js in short period of time along with ES6. Build a Newsapp while learning.

A complete beginners guide to Web Development. Master the art of building Responsive web pages with this course. Learn to code from scratch!

How to use Events and Listeners in Laravel?



Asked by Anonymous 9 months ago

An example of using Events and Listeners in laravel.


Answered by Ryan Dhungel 9 months ago

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.



Add your answer

×

Hi! Please sign in to add your answer.