easy laravel observer example
Example 1: 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 2: 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);
}
}