3

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 ;)

Melvin Koopmans
  • 2,994
  • 2
  • 25
  • 33

1 Answers1

7

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.

nehalist
  • 1,434
  • 18
  • 45
  • 1
    Thanks! exactly what I needed :) This makes it way easier to test my controllers. – Melvin Koopmans Jul 01 '14 at 21:43
  • Hi @Melvin Koopmans, I want to fire an event when a user logs in. I am using laravel 5 built in auth. Where should I fire the event? – Hassan Saqib Apr 14 '15 at 07:57
  • You can fire the event in the controller. When you hit the specific controller method, then you can define your event fire. Then, laravel automatically fire your event for you. – VijayRana Feb 20 '16 at 02:42