Showing posts with label laravel 8 when to use events. Show all posts
Showing posts with label laravel 8 when to use events. Show all posts

How To Create Event Example In Laravel 8?

How To Create Event Example In Laravel 8?

Hi Dev,

Today,I will learn you how to create event example in laravel 8.We will show simple event example in laravel 8.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 8 application. event is very help to create proper progmamming way. First create event using bellow command.

Step 1: Create Event
php artisan make:event SendMail
Next ,you can see file in this path

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

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class SendMail
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $userId;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($userId)
    {
        $this->userId = $userId;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('channel-name');
    }
}
Step 2: Listener

Now, I 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 8?. Then you have to put bellow code on app/Listeners/SendMailFired.php.

<?php

namespace App\Listeners;

use App\Events\SendMail;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use App\Models\User;
use Mail;

class SendMailFired
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  SendMail  $event
     * @return void
     */
    public function handle(SendMail $event)
    {
        $user = User::find($event->userId)->toArray();

        Mail::send('eventMail', $user, function($message) use ($user) {
            $message->to($user['email']);
            $message->subject('Event Testing');
        });
    }
}
Step 3: Providers

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.

<?php

namespace App\Providers;

use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;
use App\Events\SendMail;
use App\Listeners\SendMailFired;

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        Registered::class => [
            SendEmailVerificationNotification::class,
        ],
        SendMail::class => [
            SendMailFired::class,
        ],
    ];

    /**
     * Register any events for your application.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
}
Step 4:Create Route

Now In This Setp, we are create route.

use App\Http\Controllers\EventController;
Route::get('/event', [EventController::class, 'index'])->name('event.index');
Step 5: Create Controller

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

app/Http/Controllers/EventController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Event;
use App\Events\SendMail;

class EventController extends Controller
{
    public function index()
    {
    	Event::dispatch(new SendMail(1));
    	dd('hi');
    }
}

Now we are ready to run our event example with laravel 8 so run bellow command for quick run:

php artisan serve

Now you can open bellow URL on your browser:

localhost:8000/event

It will help you...