Getting the user who creates a model

I’m trying to store a user_id of the user who creates a model.
It can be a Rainlab/User or a backend/user.

I’m exploring the plugin Rainlab/User and its way of handling the UserLog / User Activity Timelines.
In the UserLog model, I can see a column created_user_id that is used to display a backend admin user name if the column is not null. Which is what I am looking to do.

But I can’t see anywhere in the plugin code how or when this column is filled.

Anyone has already explored this before?

Hey @chris,

You could create a behavior and attach it to any controller. In the behavior’s __construct method, you can bind to the model’s beforeCreate event like this:

$this->model->bindEvent('model.beforeCreate', [$this, 'setCreator']);

In the setCreator method, you can then store the user_id and user_type—either directly on the model or by saving them to a custom history model.

1 Like

I just found this useful mechanism, genius ~
this is this trait who handles everything automatically
use \October\Rain\Database\Traits\UserFootprints;

Traits are great and, from what I’ve heard, generally more efficient than behaviors. The main limitation is that you can’t use traits to dynamically extend a model, whereas behaviors support that. So it really depends on what you’re trying to achieve.