Laravel How to

Laravel : Best Way to setting created_by user’s ID Eloquent

When creating a new record, where the best way we should be setting the created_by user’s ID? Not only created_by, sometimes we need put uuid when inserting and set updated_by when update the row.. so what the best practice to do that ?

I know it’s very old but many people still doing the manual way. I’m not saying it wrong but for me it’s like wasting your time and will little hard to maintain.

Ok, let’s say we have article table which is have column named created_by, updated_by. Every time user insert data to article table it always need insert current user id to created_by column.

so what “manual” people do ?
For some person they doing it on controller like this :

public function store() {
$data = Request::all();
$data['created_by'] = Auth::user()->id;
Article::create($data);
...

Yes it will work but every time you save the article, you always need set value manually before. Scariest part is what if some guy forgot to set it ?

Best practice ?

in my opinion the best way to do that is using https://laravel.com/docs/4.2/eloquent#model-observers

Because we only need one time changes on the Model and it can add many additional stuff automatically by laravel.

Even if you don’t want to create observers file, you better doing simple thing like this on your Model.

public static function boot()
    {
       parent::boot();
       static::creating(function($model)
       {
           $user = Auth::user();
           $model->created_by = $user->id;
       });

       static::updating(function($model)
       {
           $user = Auth::user();
           $model->updated_by = $user->id;
       });
   }

Again, this is only my opinion. you may have different idea. Please comment if you have better solution for this.

Hope this article helps you. Have a great day.

Leave a Comment

Your email address will not be published. Required fields are marked *