Search code examples
eventslaravellaravel-4listenershandlers

Laravel Event Handlers & Listeners


I have a question about Laravel's Event Handlers and Listeners. I have no idea where to start.

I would like to know what exactly are Events and when to use them. Also I would like to know what the best way to organize events and listeners is, and where to place them (in which folder).

Any help would be appreciated ;)


Solution

  • I've recently implemented a feed for actions, e.g. when a post is created, a new user is registered, or whatever. Every action fires an event and for every event there's a listener, which saves something like "User XY just registered!" in the database.

    Very basic version:

    // app/controllers/RegistrationController.php
    class RegistrationController {
        public function register($name) {
            User::create([
                'name' => $name
            });
    
            Event::fire('user.registered', [$name]);
        }
    }
    
    // app/events.php
    Event::listen('user.registered', function($name) {
        DB::table('feed')->insert(
            [
                'action' => 'User ' . $name . ' just registered!'
                // ...
            }
        );
    });
    

    To use the events.php file, add the following line to your app/start/global.php

    require app_path().'/events.php';
    

    Now you can put all events in the events.php.


    But if you're going to have a lot of events, you shouldn't put all of your events in a single file. See Event Subscribers.