create observer in laravel code example
Example 1: create observer in laravel
php artisan make:observer nameOfObserver --model=modelName
Example 2: laravel observer
php artisan make:observer UserObserver --model=User
Example 3: 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 4: 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 5: 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);
}
}