laravel observer code example

Example 1: create observer in laravel

php artisan make:observer nameOfObserver --model=modelName

Example 2: laravel delete where

DB::table('users')->where('id', $id)->delete();

Example 3: laravel observer

php artisan make:observer UserObserver --model=User

Example 4: laravel create model and migration

# If you would like to generate a database migration when you 
# generate the model, you may use the --migration or -m option:

php artisan make:model Flight --migration
php artisan make:model Flight -m

Example 5: laravel observer

<?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)
    {
        //
    }

    /**
     * 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 "forceDeleted" event.
     *
     * @param  \App\Models\User  $user
     * @return void
     */
    public function forceDeleted(User $user)
    {
        //
    }
}

Example 6: laravel observer

<?php

namespace App\Providers;

use App\Observers\UserObserver;
use App\Models\User;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        User::observe(UserObserver::class);
    }
}

Tags:

Misc Example