observer laravel 8 code example
Example 1: laravel observer
php artisan make:observer UserObserver --model=User
Example 2: model observer laravel
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $table = 'posts';
protected $fillable = ['title', 'slug', 'content'];
protected static function boot()
{
parent::boot();
static::saving(function ($model) {
$model->slug = str_slug($model->title);
});
}
}
Example 3: laravel observer
<?php
namespace App\Observers;
use App\Models\User;
class UserObserver
{
public function created(User $user)
{
}
public function updated(User $user)
{
}
public function deleted(User $user)
{
}
public function forceDeleted(User $user)
{
}
}
Example 4: laravel observer
<?php
namespace App\Providers;
use App\Observers\UserObserver;
use App\Models\User;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function register()
{
}
public function boot()
{
User::observe(UserObserver::class);
}
}