kriszpchicken's avatar

Add created by & updated by to data

I am creating an application right now, where you can add different tasks. These tasks have a title, a description, a status, a created by, a created at, an updated by and an updated at. Created at and updated at come automatically in laravel, but I would like to also add a way to see which user created the task, and which user updated it. Unfortunately I don't really know where to start, so any help would be highly appreciated.

0 likes
3 replies
Ashraam's avatar

You you use the model observers (https://laravel.com/docs/7.x/eloquent#observers )

or you can add a boot method inside your model like this:

protected static function boot()
{
  parent::boot();
  
  static::created(function($model) {
    $model->created_by = auth()->id();
  });

  static::updated(function($model) {
   $model->updated_by = auth()->id();
  });
}
kriszpchicken's avatar

Thank you! And how should I put this in my migrations? Just put it as an increment and reference the user table?

Please or to participate in this conversation.