How to create event and listener in laravel ?

Created at 19-Jul-2023 , By samar

In this article, we will learn how to create event and listener in Laravel. Here we will log the user information to user_logs table using event and listener. The purpose of events and listeners in Laravel is to enable event-driven programming and provide a flexible and scalable way to handle various actions and processes.

Events:

Events in Laravel represent specific occurrences or actions within your application. They can be triggered when certain conditions are met, such as user registration, data updates, or system events.

Listeners:

Listeners in Laravel are responsible for handling events and performing specific actions or tasks when an event is fired. Listeners are classes that implement the Illuminate\Contracts\Events\Listener interface. Each listener is associated with one or more events, and it defines the actions to be taken when those events occur.

Here is step by step guide how you can create an event and listener to purform the specific task.

  1. Create event using php artisan command.
php artisan make:event UserLoggedIn

Add the below code in UserLoggedIn.php file created by php artisan make:event UserLoggedIn command under app\Events\UserLoggedIn.php directory.

<?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;
use App\Models\User;

class UserLoggedIn
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    /**
     * Create a new event instance.
     */
    public $user;
    public function __construct(User $user)
    {   
        $this->user = $user;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return array<int, \Illuminate\Broadcasting\Channel>
     */
    public function broadcastOn(): array
    {
        return [
            new PrivateChannel('channel-name'),
        ];
    }
}
  1. Now you have to create the listener. You can use below command to create the listener in Laravel.
php artisan make:listener LogUserLogin

Add code in LogUserLogin.php file under app\Listeners directory.

<?php

namespace App\Listeners;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use App\Events\UserLoggedIn;
use App\Models\Log;

class LogUserLogin
{
    /**
     * Create the event listener.
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     */
    public function handle(UserLoggedIn $event): void
    {
        $user = $event->user;

        // Create a log entry in the 'logs' table
        Log::create([
            'user_id' => $user->id,
            'description' => 'User logged in: ' . $user->name,
        ]);
    }
}
  1. Migration for user_logs table. Run migration command.
php artisan make:migration create_user_logs_table --create=user_logs

Add below code in migration file generated by above artisan command.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('user_logs', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id');
            $table->string('description');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('user_logs');
    }
};
  1. Create the Log model.
php artisan make:model Log

Add below code in your app\Models\Log.php file.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Log extends Model
{
    use HasFactory;

    protected $table = "user_logs";
    protected $fillable = [
        'user_id', 'description'
    ];

}
  1. Make changes in web.php file routes\web.php directory.

routes\web.php

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::get('/call-event-listener', [App\Http\Controllers\HomeController::class, 'callEventListener']);
  1. Create a method to call the event in HomeController class.
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        return view('home');
    }


    public function callEventListener(){
        $user = User::findOrFail(1);
        event(new UserLoggedIn($user));
        echo "Event and listener called successfully !";
    }
}
  1. Add event to listen property of eventserviceprovider.

laravel\app\Providers\EventServiceProvider.php

<?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\Listeners\LogUserLogin;
use App\Events\UserLoggedIn;

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event to listener mappings for the application.
     *
     * @var array<class-string, array<int, class-string>>
     */
    protected $listen = [
        Registered::class => [
            SendEmailVerificationNotification::class,
        ],
        UserLoggedIn::class => [
            LogUserLogin::class
        ],
    ];

    /**
     * Register any events for your application.
     */
    public function boot(): void
    {
        //
    }

    /**
     * Determine if events and listeners should be automatically discovered.
     */
    public function shouldDiscoverEvents(): bool
    {
        return false;
    }
}

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.