How to create event and listener in laravel - TechvBlogs

How to create event and listener in laravel

In this article, You will learn How to create event and listener in laravel.


Smit Pipaliya - Author - TechvBlogs
Smit Pipaliya
 

2 months ago

TechvBlogs - Google News

In this comprehensive guide, we'll delve into the process of creating events and listeners in Laravel, focusing on logging user information to the user_logs table. Understanding events and listeners in Laravel is essential for embracing event-driven programming and ensuring a flexible and scalable approach to handling various actions and processes.

Events and Listeners in Laravel

Events

Events in Laravel signify specific occurrences or actions within your application. These events are triggered based on certain conditions, such as user registration, data updates, or system events.

Listeners

Listeners in Laravel play a pivotal role in handling events. They are responsible for executing specific actions or tasks when an event is fired. Each listener is associated with one or more events and defines the actions to be taken when those events occur.

Step-by-Step Guide to Creating an Event and Listener

1. Create Event Using Artisan Command

Use the following Artisan command to generate a new event:

php artisan make:event UserLoggedIn

This command creates a new event file, UserLoggedIn.php, in the app\Events directory.

2. Define Event Code

In the generated UserLoggedIn.php file, add the code to capture user information:

namespace App\Events;

use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
use App\Models\User;

class UserLoggedIn
{
    use Dispatchable, SerializesModels;

    public $user;

    public function __construct(User $user)
    {   
        $this->user = $user;
    }
}

3. Create Listener Using Artisan Command

Generate a new listener using the Artisan command:

php artisan make:listener LogUserLogin

This creates a LogUserLogin.php file in the app\Listeners directory.

4. Define Listener Code

In the generated LogUserLogin.php file, implement the code to log user login information:

namespace App\Listeners;

use App\Events\UserLoggedIn;
use App\Models\Log;

class LogUserLogin
{
    public function handle(UserLoggedIn $event): void
    {
        $user = $event->user;

        // Create a log entry in the 'user_logs' table
        Log::create([
            'user_id' => $user->id,
            'description' => 'User logged in: ' . $user->name,
        ]);
    }
}

5. Create Migration for user_logs Table

Run the migration command to create the user_logs table:

php artisan make:migration create_user_logs_table --create=user_logs

Add the necessary code in the generated migration file.

6. Create Log Model

Generate a model for the user_logs table:

php artisan make:model Log

Define the model in the app\Models\Log.php file:

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'];
}

7. Update Routes and Controller

Modify the web.php file in the routes directory and the HomeController.php file to include a method to call the event.

8. Add Event to EventServiceProvider

In the EventServiceProvider.php file located in the app\Providers directory, add the UserLoggedIn event to the $listen property.

9. Test the Event and Listener

Run your Laravel application and navigate to the route associated with calling the event. Confirm that the event and listener are working successfully.

By following these steps, you've successfully implemented events and listeners in Laravel, enhancing your ability to handle specific actions and processes in a structured and organized manner.

Comments (0)

Comment


Note: All Input Fields are required.