It sounds like you're trying to use model observers to automatically set created_by, updated_by, and deleted_by attributes on your Eloquent model when certain events occur. If these events are not firing when using route model binding, it could be due to a few reasons. However, route model binding itself should not prevent model events from firing.
Here's a solution that should work regardless of whether you're using route model binding or the find method:
First, ensure that your observer is registered correctly in your AppServiceProvider or a dedicated provider:
use App\Models\YourModel;
use App\Observers\YourModelObserver;
/**
* Register any application services.
*
* @return void
*/
public function register()
{
// ...
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
YourModel::observe(YourModelObserver::class);
}
Next, create the observer if you haven't already:
namespace App\Observers;
use App\Models\YourModel;
use Illuminate\Support\Facades\Auth;
class YourModelObserver
{
public function creating(YourModel $model)
{
$model->created_by = Auth::id();
}
public function updating(YourModel $model)
{
$model->updated_by = Auth::id();
}
public function deleting(YourModel $model)
{
$model->deleted_by = Auth::id();
$model->save();
}
// You can also define restored() if you're using soft deletes
}
Make sure that you're not using mass assignment for these fields, or if you are, that they are included in the $fillable array of your model:
class YourModel extends Model
{
protected $fillable = [
// ... other attributes ...
'created_by',
'updated_by',
'deleted_by',
];
}
If you're using soft deletes and want to handle the deleting event, remember that you need to call save() after setting the deleted_by attribute, as shown in the observer above. This is because the deleting event is called before the model is actually deleted, so you need to persist the deleted_by attribute manually.
Lastly, ensure that the authenticated user is available when the events are fired. If these events are triggered before the session middleware runs (which is responsible for authenticating users), Auth::id() will return null.
If you've done all of this and the events are still not firing, you may need to debug further. Check if the observer methods are being called at all by adding logging or dumping data. Also, ensure that there are no global scopes or other query modifications interfering with the model events.
Remember that if you're using a form request or any other type of request validation, you should ensure that the observer is not dependent on the request lifecycle, as the model might be saved outside of the request's scope.