简体   繁体   中英

How to perform simple audit trail in simple CRUD laravel

how to get the username of the last person who update the form,using the ( updated_at ) timestamp in laravel and what is the best logic or approach to do?is it possible to use in blade only? or should i need to put the code in my controller?

Example: Updated:13-Jun-2018 UpdatedBy: Username

currently i can only get the updated date by using this code in my blade

Updated:{{ date('d-M-Y', strtotime($leads->updated_at))}}

You need this two columns in your database table : updated_at and last_updated_by

in your controller , when you are updating that record , add id of user who is updating the record in last_updated_by field .

note : this will display only last updated by user id .

if you want to store each updated_by then make a new table :

   table:  update_timeline

   postid : user_id : updated_date 

now you can use join query for these two tables and get every updated by , if you want .

Database Table

CREATE TABLE `leads` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `lead_history` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `lead_id` int(11) unsigned DEFAULT NULL,
  `updated_by` int(11) unsigned DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Models

class Lead extends Model {

    public function history()
    {
        return $this->hasMany(LeadHistory::class,'lead_id');
    }

}
class LeadHistory extends Model{

    public function lead()
    {
        return $this->belongsTo(Lead::class);
    }

    public function user()
    {
        return $this->belongsTo(User::class, 'updated_by');
    }
}

Now Fetch the leads

$leads = Lead::all(); //for demo purpose, always use pagination based results or fetch with condition

Here is the template rendering

@foreach ($leads as $lead)
    <p>This is your lead: {{ $lead->name }}</p>
      @if ($lead->history)
        <label>Lead Updated By:</label>
        <ul>
           @foreach ($lead->history as $history)
              <li>{{$history->user->username}}</li>
            @endforeach
        </ul>
      @endif
 @endforeach

Assuming you have user table with "username" field

Whenever user update the lead, you just need to insert a record in lead history table with that userId in updated_by field

You could store model changes in a separate model, say Activity . This model could have a polymoprhic relationship to a model, a foreign key to the user that performed the activity, and the type of operation (ie create , update , delete ).

You could then create a trait that you apply to models that automatically creates an activity record each time a model is created, updated, or deleted:

trait Auditable
{
    public static function bootAuditable()
    {
        static::created(function ($model) {
            $model->recordActivity('create');
        });

        static::updated(function ($model) {
            $model->recordActivity('update');
        });

        static::deleted(function ($model) {
            $model->recordActivity('delete');
        });
    }

    protected function recordActivity($operation)
    {
        $activity = new Activity([
            'operation' => $operation,
            'user_id' => Auth::id(),
        ]);

        $activity->model()->associate($this);

        $activity->save();
    }
}

You'll then be able to crudely list operations for a model, ie

  1. User 1 created Model 1
  2. User 2 updated Model 1
  3. User 1 created Model 2
  4. User 1 deleted Model 1

…and so on.

I've created a package for created_by, updated_by audit trails. You can check it out at https://github.com/insenseanalytics/laravel-user-audit-trails

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM