Events provides easy viewing usage, allowing you to register and listen to events in your app. In this post you can learn how to create an email event in your laravel 5.2 program. the event is very helpful in creating the right way forward. First create an event using the bellow command.
php artisan make:event SendMail
Okay, you can now see the file this way app/Events/SendMail.php and enter the valid code in that file.
app/Events/SendMail.php
<?php
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 an event for the "SendMail" event. So create an event listener using the bellow command.
php artisan make:listener SendMailFired --event="SendMail"
In this event listener we must process the event code, even the postal code, Before this file you must check your post configuration.
After that you have to put a following code in the app/Listeners/SendMailFired.php.
app/Listeners/SendMailFired.php
<?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->to($user['email']);
$message->subject('Event Testing');
});
}
}
?>
Now we need to register the event in the EventServiceProvider.php file so, open the application/Providers/EventServiceProvider.php and copy this code and paste it into your file.
applicatio /Providers/EventServiceProvider.php
<?php
namespace AppProviders;
use IlluminateContractsEventsDispatcher as DispatcherContract;
use IlluminateFoundationSupportProvidersEventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider {
protected $listen = [
'AppEventsSomeEvent' => [
'AppListenersEventListener',
],
'AppEventsSendMail' => [
'AppListenersSendMailFired',
],
];
public function boot(DispatcherContract $events) {
parent::boot($events);
}
}
?>
We're finally ready to run the event in our controller file. so use this method:
<?php
namespace AppHttpControllers;
use AppHttpRequests;
use IlluminateHttpRequest;
use Event;
use AppEventsSendMail;
class HomeController extends Controller {
public function __construct() {
$this->middleware('auth');
}
public function index() {
Event::fire(new SendMail(2));
return view('home');
}
}
?>