Created
November 25, 2019 10:03
-
-
Save Hanson/b8916bf13c38336f8eb33e537fab3723 to your computer and use it in GitHub Desktop.
Laravel global model's log. You can rerord the admin's operation.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(), | |
]); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
感谢楼主分享,还可以看下这个包 https://github.com/spatie/laravel-activitylog