How to create an event in laravel
Here is the following Laravel event listener step by step process with Example. An event is an action or occurrence that will happen in your application. The Application will raise events when something happens.
Lets Create Events In Laravel. We will create simple event which fired an event on call of rest api end points.
Step 1: Register Laravel Events and Listeners
Laravel provides EventServiceProvider where we can register our events and their corresponding listeners.
#app/Providers/EventServiceProvider.php
class EventServiceProvider extends ServiceProvider
{
protected $listen = [
'App\Events\UserRegistered' => [
'App\Listeners\SendUserEmail',
],
];
}
We need to generate our Laravel events by running the command:
php artisan event:generate
app/Events you will find the file UserRegistered.php. And SendUserEmail.php file should placed in the app/Listeners folder.
Step 2: Defining Events and Listeners
Now open this file and Your goal is to send a User email to the user after they registered.
#app/Events/UserRegistered.php
namespace App\Events;
use App\User;
class UserRegistered
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $user;
public function __construct(User $user)
{
$this->user = $user;
}
}
Open our listener SendUserEmail and write the code as follows.
#app/Listeners/SendUserEmail.php
namespace App\Listeners;
use Mail;
class SendWelcomeEmail
{
public function handle(UserRegistered $event)
{
$data = array('name' => $event->user->name, 'email' => $event->user->email, 'body' => 'Welcome our website.');
Mail::send('emails.mail', $data, function($message) use ($data) {
$message->to($data['email'])
->subject('Welcome our Website');
$message->from('noreply@yoursite.com');
});
}
}
We should have resources/views/emails/mail.blade.php file in our project.
#mail.blade.php
Hello, <b>{{ $name }}</b>,
<p>{{ $body }}</p>
Step 3: Event Call
#app/Http/Controllers/Auth/RegisterController.php
namespace App\Http\Controllers\Auth;
use App\Events\UserRegistered;
class RegisterController extends Controller
{
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
event(new UserRegistered($user));
return $user;
}
}
Now you can create User then send a welcome email to the user.