5.3 C
New York
Tuesday, December 6, 2022

How to create Event for Mail sending in Laravel 5.2?

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 5.2 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 AppEvents;

use AppEventsEvent;

use IlluminateQueueSerializesModels;

use IlluminateContractsBroadcastingShouldBroadcast;

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, If you did not set then you can set this way :How to set gmail configration for mail in Laravel?.

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


namespace AppListeners;

use AppEventsSendMail;

use IlluminateQueueInteractsWithQueue;

use IlluminateContractsQueueShouldQueue;

use AppUser;

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

use IlluminateContractsEventsDispatcher as DispatcherContract;

use IlluminateFoundationSupportProvidersEventServiceProvider as ServiceProvider;

class EventServiceProvider extends ServiceProvider


protected $listen = [

'AppEventsSomeEvent' => [



'AppEventsSendMail' => [




public function boot(DispatcherContract $events)





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


namespace AppHttpControllers;

use AppHttpRequests;

use IlluminateHttpRequest;

use Event;

use AppEventsSendMail;

class HomeController extends Controller


public function __construct()




public function index()


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

return view('home');



Ok Now check in your application,

Happy Code……

Related Articles


Please enter your comment!
Please enter your name here

Latest Articles