Laravel Activity Log won't work on Update

3.4k Views Asked by At

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

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');
3

There are 3 best solutions below

0
On BEST ANSWER

The Update with writing in DB but NOT writing in ActivityLogs will look like this:

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

The Update with writing in DB and ALSO writing in ActivityLogs will look like this:

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.

1
On

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();
}
1
On

I have changed my query. we should use Eloquent query.

$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');