generated from spatie/package-skeleton-laravel
-
Notifications
You must be signed in to change notification settings - Fork 4
/
ModelBlamer.php
56 lines (45 loc) · 1.47 KB
/
ModelBlamer.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<?php
namespace Kamansoft\LaravelBlame\Traits;
use Illuminate\Support\Facades\Auth;
trait ModelBlamer
{
use UserModelForAuth;
protected static function bootModelBlamer()
{
static::creating(function ($model) {
$model->blameOnCreate();
});
static::updating(function ($model) {
$model->blameOnUpdate();
});
}
public function blameOnCreate()
{
$creator_field_name = config('blame.created_by_field_name');
$updater_field_name = config('blame.updated_by_field_name');
$this->$creator_field_name = $this->$updater_field_name = $this->getUserToBlamePk();
}
public function getUserToBlamePk(): string
{
$to_return = '';
if (Auth::check()) {
$to_return = Auth::user()->getKey();
} else {
$to_return = config('blame.system_user_id');
}
return $to_return;
}
public function blameOnUpdate()
{
$updater_field_name = config('blame.updated_by_field_name');
$this->$updater_field_name = $this->getUserToBlamePk();
}
public function creator(): BelongsTo
{
return $this->belongsTo(config('auth.providers.users.model'), config('blame.created_by_field_name'), $this->getUsersModelPkName());
}
public function updater(): BelongsTo
{
return $this->belongsTo(config('auth.providers.users.model'), config('blame.updated_by_field_name'), $this->getUsersModelPkName());
}
}