How to create event and listener in laravel ?
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.
- 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'),
];
}
}
- 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,
]);
}
}
- 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');
}
};
- 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'
];
}
- 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']);
- 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 !";
}
}
- 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.
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.
Random Code Snippet Queries: Laravel
- Pass variable from blade to controller Laravel
- How to fetch single row data from database in laravel
- Method Illuminate\Database\Eloquent\Collection::lists does not exist
- The POST method is not supported for this route. Supported methods: PUT.
- How to check relationship is loaded or not in Laravel
- After image selected get validation error in laravel
- Fatal error: Composer detected issues in your platform: Your Composer dependencies require a PHP version ">= 8.0.0"
- Call to a member function update() on null
- On delete set foreign id column value null using migration in laravel 8
- Get last record from table in laravel
- How to call controller function from view in Laravel
- Create records using relationship in laravel
- How to upload image in laravel 8
- Conditional where clause in Laravel
- Save or update pivot table data with additional column in Laravel
- Display data in table using foreach in Laravel
- How to pass data to multiple partial view files in laravel
- How to create belongstomany relation using custom name on custom pivot table
- Calculate age from date of birth in Laravel
- How to add a key value pair to existing array in laravel
- How to implement toggleLike() method in Overtrue\LaravelLike laravel package
- Wheredate in laravel not working
- How to check email is valid or not in Laravel
- FirstOrCreate() Not Inserting Model
- Add class to body in laravel view