Skip to content

Instantly share code, notes, and snippets.

@Hanson
Created November 25, 2019 10:03
Show Gist options
  • Save Hanson/b8916bf13c38336f8eb33e537fab3723 to your computer and use it in GitHub Desktop.
Save Hanson/b8916bf13c38336f8eb33e537fab3723 to your computer and use it in GitHub Desktop.
Laravel global model's log. You can rerord the admin's operation.
<?php
namespace App\Providers;
use App\Models\AdminLog;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\ServiceProvider;
class LogServiceProvider extends ServiceProvider
{
/**
* Register services.
*
* @return void
*/
public function boot()
{
Event::listen('eloquent.*', function ($eventName, $data) {
if (preg_match('/eloquent\.(.+):\s(.+)/', $eventName, $match) === 0) {
return;
}
/** $match @val array
array (
0 => 'eloquent.booting: App\\Models\\Groupon',
1 => 'booting',
2 => 'App\\Models\\Groupon',
)
*/
// only record when 'created', 'updated', 'deleted'
if (!in_array($match[1], ['created', 'updated', 'deleted'])) {
return;
}
// only record the admin operation.
if (!Auth::guard('admin')->check()) {
return;
}
$model = $data[0];
$class = get_class($model);
$diff = array_diff_assoc($model->getOriginal(), $model->getAttributes());
$keys = array_keys($diff);
$data = [];
foreach ($keys as $key) {
if ($key === 'updated_at') {
continue;
}
$data[$key] = [
'old' => $model->getOriginal($key),
'new' => $model->getAttributes()[$key]
];
}
$admin = Auth::guard('admin')->user();
// You can create the table with your situation
AdminLog::query()->create([
'admin_id' => $admin->id,
'url' => request()->fullUrl(),
'action' => $match[1], // updated created deleted
'ip' => request()->getClientIp(),
'model_id' => $model->id,
'model_type' => $class,
'data' => $data,
'created_at' => now(),
]);
});
}
}
@Hanson
Copy link
Author

Hanson commented Nov 26, 2019

@kylesean 这个也可以,所以我没做成包的形式,代码段的形式更加简单方便修改,根据自身需求实现即可

@bolechen
Copy link

感谢楼主分享,还可以看下这个包 https://github.com/spatie/laravel-activitylog

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment