Laravel listen eloquent events using Observers example

If you want to listen many events for any model, you may want to use observers. Laravel Observers groups all of the listeners into a single class. This will help in managing to listen listen all events in a single class.

Laravel Observer contains methods which listen for the eloquent events you want to set for. In this article, we will create Observer and listen for few events.

Laravel observers moniters for following events to listen:

retrieved : after a record retrieved
creating : before a record created
created : after a record created
updating : before a record updated
updated : after a record updated
saving : before a record is saved
saved : after a record saved
deleting : before a record deleted
deleted : after a record deleted
restoring : before a soft deleted record restored
restored : after a soft deleted record restored

In this article, we will send welcome mail when user register. This will listen on created event. So our mail logic will added on created method.

To get started article, first create and setup new Laravel application with authentication. Follow this article and you are ready to start the tutorial.

Apart from above, we need to setup MAIL credentials in .env file as we are going to send mail when user register. Change mail configuration to .env file according to yours.

MAIL_DRIVER=sendmail
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=yourpassword
MAIL_ENCRYPTION=tls
[email protected]
MAIL_FROM_NAME="${Laravel Breeze}"

To create a new Observer, run the following artisan command. It will create observer class in app/Observers directory.

php artisan make:observer UserObserver --model=User

Now go to the UserObserver class and add mail function in created() method. You can add into additional methods according your requirement. For example, add mail function in updated() method so it will send mail when user update his/her profile.

<?php

namespace App\Observers;

use App\Models\User;

class UserObserver
{
    /**
     * Handle the User "created" event.
     *
     * @param  \App\Models\User  $user
     * @return void
     */
    public function created(User $user)
    {
        \Mail::raw('Congratulations, you have just created account on Laravel Breeze.', function ($message) {
            $message->from(env('MAIL_FROM_ADDRESS'), env('MAIL_FROM_NAME'));
            $message->to($user->email);
            $message->subject('Welcome to Laravel Breeze.');
        });
    }

    /**
     * Handle the User "updated" event.
     *
     * @param  \App\Models\User  $user
     * @return void
     */
    public function updated(User $user)
    {
        //
    }

    /**
     * Handle the User "deleted" event.
     *
     * @param  \App\Models\User  $user
     * @return void
     */
    public function deleted(User $user)
    {
        //
    }

    /**
     * Handle the User "restored" event.
     *
     * @param  \App\Models\User  $user
     * @return void
     */
    public function restored(User $user)
    {
        //
    }

    /**
     * Handle the User "force deleted" event.
     *
     * @param  \App\Models\User  $user
     * @return void
     */
    public function forceDeleted(User $user)
    {
        //
    }
}

Now we need to register observer in application. To do so, you need to call the observe() method on the model in App\Providers\EventServiceProvider service provider you want to observe:

<?php

namespace App\Providers;

use App\Models\User;
use App\Observers\UserObserver;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;

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

    /**
     * Register any events for your application.
     *
     * @return void
     */
    public function boot()
    {
        User::observe(UserObserver::class);
    }
}

That's it. Run the Laravel server using artisan command php artisan serve and go through http://localhost:8000/register in your browser. Now whenever any user registers, a welcome mail will be send to registered email address.

Was this article helpful?

0 out of 0 person found this article helpful.

Leave a comment

Or

No Comment