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.
app/Events/SendMail.php
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.
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->to($user['email']);
$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.
app/Providers/EventServiceProvider.php
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\Listeners\EventListener',
],
'App\Events\SendMail' => [
'App\Listeners\SendMailFired',
],
];
public function boot(DispatcherContract $events)
{
parent::boot($events);
}
}
At Last we are ready to use event in our controller file. so use this way:
app/Http/Controllers/HomeController.php
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()
{
$this->middleware('auth');
}
public function index()
{
Event::fire(new SendMail(2));
return view('home');
}
}