Skip to content

Extend Eloquent Model with created_by, updated_by ?

By extending Eloquent we can inherits all of the existing functionality to our model. By Extending newly created Base Model we can inherits custom methods in all models. By placing global used common methods at one place we can satisfy DRY principle.

To extend Eloquent, all you have to do is create a new class which extends Eloquent.I am going to name my model as BaseModel, so lets create BaseModel.php in your app/models directory.

In the below BaseModel, we are firing events while creating and updating records, and we are inserting and updating “created_by” and “updated_by” columns receptively.

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

How to use

For Example if you have a model called post.php

class Post extends BaseModel {
    
    public static function boot()
    {
        parent::boot();
    }
   
}

Laravel will not boot the model until it is needed because laravel uses lazy auto-loading technique. That’s it.

0 0 votes
Article Rating
Subscribe
Notify of
guest

2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments