Laravel Activity 日志在更新时不起作用

Laravel Activity Log won't work on Update

我正在使用 SPATIE laravel-activitylog 我已按照所有说明进行操作,但它仍然只记录创建函数而不是在模态上使用它时更新

我的模态框

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Spatie\Activitylog\Traits\LogsActivity;

class Contact extends Model
{
    use HasFactory, LogsActivity;
    protected $fillable = [
        'comp_name',
        'cont_name',
        'cont_email',
        'cont_number',
        'created_by',
        'updated_by',
    ];
        // spatie activitylog
    protected static $logFillable = true;
    protected static $logOnlyDirty = true;
    protected static $logName='users'; // default
}

我的控制器

 Contact::where('id',$input['id'])->update($data);
 $retrnArray = array('status'=>1,'msg'=>'Updated Successfully');

默认日志选项似乎不包括所有模型的字段。您可以描述需要记录的字段或使用通配符为每个字段更改触发记录。根据 documentation 示例(在您的模型 Class 中):

public function getActivitylogOptions(): LogOptions
{
    return LogOptions::defaults()->logOnly(['*']);
    // To avoid hardcoding you could use logAll() method
    // return LogOptions::defaults()->logAll();
}

我更改了查询。我们应该使用 Eloquent 查询。

$contact = Contact::find($input['id']);
$contact->cont_email = $input['cont_email'];
$contact->cont_number = $input['cont_number'];           
$contact->save();

$retrnArray = array('status'=>1,'msg'=>'Updated Successfully');

Update 在 DB 中写入但 NOT 在 ActivityLogs 中写入将如下所示:

User::where("id", 1)->update($data);

在 DB 中写入的 Update 和在 ActivityLogs 中写入的 ALSO 将如下所示:

User::where("id", 1)->first()?->update($data); //if you are using php >= 8
User::where("id", 1)->firstOrFail()->update($data); // Good using php >= 5.6
User::find(1)?->update($data); //This also works as find("your id") also returns the model that it was able to found, it also returns null so check it on null or use nullsafe operator.

加载模型以正确生成 ActivityLogs 很重要。