n How to create Event in Laravel | CodimTh

Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh

How to create Event in Laravel

Events provides a simple observer implementation, allowing you to subscribe and listen for events in your application. In this posts you can learn how to create event for email send in your laravel  application. event is very help to create proper progmamming way. First create event using bellow command.

php artisan make:event SendMail


Ok, now you can see file in this path


app/Events/SendMail.php and put bellow code in that file.



namespace App\Events;

use App\Events\Event;

use Illuminate\Queue\SerializesModels;

use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class SendMail extends Event


use SerializesModels;

public $userId;

public function __construct($userId)


$this->userId = $userId;


public function broadcastOn()


return [];





Next, we need to create event listener for "SendMail" event. So create event listener using bellow command.

php artisan make:listener SendMailFired --event="SendMail"

In this event listener we have to handle event code, i mean code of mail sending, Before this file you have to check your mail configration.

Then you have to put bellow code on app/Listeners/SendMailFired.php.


namespace App\Listeners;

use App\Events\SendMail;

use Illuminate\Queue\InteractsWithQueue;

use Illuminate\Contracts\Queue\ShouldQueue;

use App\User;

use Mail;

class SendMailFired


public function __construct()



public function handle(SendMail $event)


$user = User::find($event->userId)->toArray();

Mail::send('emails.mailEvent', $user, function($message) use ($user) {


$message->subject('Event Testing');





Now we require to register event on EventServiceProvider.php file so, open app/Providers/EventServiceProvider.php and copy this code and put in your file.


namespace App\Providers;

use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;

use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;

class EventServiceProvider extends ServiceProvider


protected $listen = [

'App\Events\SomeEvent' => [



'App\Events\SendMail' => [




public function boot(DispatcherContract $events)






At Last we are ready to use event in our controller file. so use this way:



namespace App\Http\Controllers;

use App\Http\Requests;

use Illuminate\Http\Request;

use Event;

use App\Events\SendMail;

class HomeController extends Controller


public function __construct()




public function index()


Event::fire(new SendMail(2));

return view('home');





Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts


Page Facebook