Presto's avatar

Where should I set a created_by to the user's ID?

Hello everyone,

When creating a new record, where should I be setting the created_by user's ID? I know it should obviously not be accessible via the form, but should I be setting that value in the controller or in the model?

This is probably not the correct way? In my model:

public function setCreatedByAttribute(){
    $this->attributes['created_by'] = Auth::user()->id;
}
0 likes
7 replies
Presto's avatar

Or in the controller

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

Hey! You could do that directly in your controller, like this, using a simple hasMany relation:

php
//In your user model:
public function articles()
{
    return $this->hasMany('App\Article');
}

Then you can easily create an article using this:

//In your user model:
public function create()
{
    Auth::user()->articles()->create($article);
}

Like this, the user field will automatically be used. And you should call it 'user_id' in your articles table.

Jeffrey Way explains that very well in the last Laravel 5 videos, you should give them a look :)

1 like
robgeorgeuk's avatar

Ever wanted to maintain an 'updated_by' field when updating a record? Here's one way:

class Article extends Model {

    public static function boot()
    {
        // Update field update_by with current user id each time article is updated.
        static::updating(function ($article) {
            $article->updated_by = Auth::user()->id;
        });
    }

}
1 like
mdshaf229's avatar

I have developed a simple package https://github.com/hmshafeeq/userstamps for handling userstamps.

It handles the following two requirements

  1. Insert userstamps automatically
  2. Autoload the userstamp model along with the original model ( it will execute one query to get all created_by, updated_by, deleted_by, submitted_by etc fields instead of making separate calls). So in your model, you don't need to define the relation with user model multiple times i.e for created_by, updated_by,....

Install the package and use it as below.

use VelitSol\UserStamps\UserStampTrait;

class Example extends Model {

    use UserStampTrait;
     
    protected $userStamps = [
       
       /==============================================
       /  Auto load userstamp model for current model.
       /==============================================
      // If you don't want this pacakge to auto insert the userstamp, 
      // and you just want to  autoload it along with your model
      // This will be the case when userstamp is being set in controller 
      // or some where else at certain action.
       'updated_by',
     
      /=========================================================
      /  Auto insert userstamp & auto load it for current model.
      /  Auto insert depends on,
      /  1. Event ('creating','saving','updating','deleting')
      /  2. Field 
      /  3. Expression
      /=========================================================
          
       // This userstamp should be updated when an event is 
       // invoked i.e 'creating','updating','deleting','saving'.
       'created_by' => [
            'depends_on_event' => 'creating', 
       ],
       'deleted_by' => [
             'depends_on_event' => 'deleting', 
       ],
       
       // This userstamp should be set if "is_archived" is dirty (has some changes in value)
       'archived_by' => [
            'depends_on_field' => 'is_archived' 
       ],
       
       // This userstamp should be set if "updating" event is invoked on this model,
       // and "is_submitted" is dirty (has some changes in value)
       'submitted_by'=> [
            'depends_on_event' => 'updating', 
            'depends_on_field' => 'is_submitted' 
       ],
       
       // This userstamp should be set if "updating" event is invoked on this model,
       // and provided expression evaluates to true
       'suspended_by' => [
          'depends_on_event' => 'updating', 
          // $api_hits is a model field i.e $model->api_hits
          'depends_on_expression' => '$api_hits > 100' 
       ],
       .............,
       ..............,
    ];
}
yash54's avatar

Hey Mate, just add one boot function to the model which created_by and updated_by record you want.

Here you go,

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

add this function in your model and you can see user's created_by and updated_by id.

Hope my answer helps you. Have a great day.

6 likes

Please or to participate in this conversation.