Purpose of using an observer
We had a request to "record which user modified the data," so we ended up storing the creator, editor, and deleter of each record in the DB.
What we did
Add creator, editor, and deleter columns to every table
Create a migration file (example)
php artisan make:migration add_creator_editor_deleter_to_all_table
Create Observer.php to catch CRUD events
namespace App\Observers;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
class xxxObserver
{
public function created(Model $model)
{
// Logic to register the creator after data is saved
}
public function updated(Model $model)
{
// Logic to register the editor after data is updated
}
public function deleted(Model $model)
{
// Logic to register the deleter after data is deleted
}
}
Create a Trait so the Observer gets wired up
namespace App\Traits;
use App\Observers\xxxObserver;
trait xxxObservable
{
public static function bootxxxObservable()
{
self::observe(xxxObserver::class);
}
}
Then just summon it in the Model
namespace App\Models;
use App\Traits\xxxObservable; // The Trait we just created
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
use xxxObservable;
// omitted
}
The overall flow turned out to be surprisingly simple. The best part is that once you create a single observer, you can call it from any Model you want and get the same shared behavior. It's convenient, so I'd like to keep using it whenever the opportunity comes up.