简体   繁体   English

Laravel 活动日志不适用于更新

[英]Laravel Activity Log won't work on Update

I'm using SPATIE laravel-activitylog I followed all the instructions but still it only log the Create function not update while using it on a Modal我正在使用 SPATIE laravel-activitylog 我遵循了所有说明,但它仍然只记录 Create 函数,而不是在 Modal 上使用它时更新

My Modal我的模态

<?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
}

My Controller我的控制器

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

I have changed my query.我已经改变了我的查询。 we should use Eloquent query.我们应该使用 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');

It seems the default log options does not include all Model`s field.似乎默认日志选项不包括所有模型的字段。 You can describe fields that needs logging or use the wildcard to fire logging for every field changes.您可以描述需要记录的字段或使用通配符为每个字段更改触发日志记录。 According to documentation example (in your Model Class):根据文档示例(在您的模型类中):

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

The Update with writing in DB but NOT writing in ActivityLogs will look like this:在 DB 中写入但不在ActivityLogs 中写入的更新将如下所示:

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

The Update with writing in DB and ALSO writing in ActivityLogs will look like this:在DB写作和ActivityLogs看起来像这写入更新

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.

It's important to load model to make ActivityLogs correctly.加载模型以正确制作 ActivityLogs 很重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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