How to create an event in Laravel

Author - Webner
20.11.2020
|
0 Comments
||

Laravel events provide an observable functionality, allowing you to subscribe and listen. Events are stored in the app/Events directory and their listeners are stored in the app/Listener directory. We can generate a Laravel event by running

“php artisan event:generate” command.

Register event and listeners :

The EventServiceProvider file provides a place to register both events and listeners for your project. The listen property contains an array of listeners. We can create any number of events according to our needs.

code

Generating Events & Listeners :

It is very difficult to create events manually. We can generate the events with the help of command. Write all the events in the EventServiceProvider file and then execute the event:generate command to create all the events listed in the file.

code1 laravel

  • How to Call an event:
    use App\Events\NewUserRegistered;
    class RegisterController extends Controller
    {
    public function verifyEmail(Request $request)
    {
    $user = ‘User detail’;
    event(new NewUserRegistered($user));
    }
    }
  • How to Write an event
    class NewUserRegistered
    {
    use Dispatchable, InteractsWithSockets, SerializesModels;
    public $user;
    /**
    * Create a new event instance.
    *
    * @return void
    */
    public function __construct($user)
    {
    $this->user = $user;
    }
    }
  • How to write a listener
    use App\Events\NewUserRegistered;
    class NewUserRegisteredListener implements ShouldQueue
    {
    /**
    * Handle the event.
    *
    * @param NewUserRegistered $event
    * @return void
    */
    public function handle(NewUserRegistered $event)
    {
    // use event variable to get user detail
    // Here we can write code to send an email or whatever you want to do
    }
    }
Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

Your email address will not be published. Required fields are marked *