Laravel Spatie - Custom Attribute value when audit log via modal

1.3k Views Asked by At

on my modal, I have two functions which I have used to log the data when it has been changed. those are below.

namespace App\Models;

use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;
use Spatie\Activitylog\Contracts\Activity;
use Illuminate\Support\Facades\Auth;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Receivinglogentry extends Model
{
    use HasFactory;
    use LogsActivity;

    protected $fillable = [
        'status',
        'amt_shipment',
        'container',
        'po',
        'etd_date',
        'eta_date',
    ];

    protected $casts = [
        'po_ref' => 'json',
    ];

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()->logOnly(['*'])->logOnlyDirty();
    }

    public function tapActivity(Activity $activity,string $eventName)
    {
        $current_user = Auth::user()->name;
        $event        = $activity->attributes['event'];
        $data         = $activity->relations['subject']->attributes['container'];
        $masterID     = $activity->relations['subject']->attributes['id'];

        $activity->description   = "{$current_user} has {$event} Container : {$data}";
        $activity->causer_name   = $current_user;
        $activity->master_id     = $masterID ;
        $activity->log_name      = 'Receivinglogentry';
    }
}

fillable data status has been stored as an integer value. but I have to log it as a string value something like PENDING or ACTIVE. any recommendation to log attributes customizably is appricated.

1

There are 1 best solutions below

0
On

You can try ENUM concept but in Laravel 9 onwards. Here is a reference link - https://enversanli.medium.com/how-to-use-enums-with-laravel-9-d18f1ee35b56

There they describe about an enum UserRoleEnum:string which you can format as your own requirement. In your case, the key itself is a number. So I suggest to make it as string as below.

enum StatusEnum:string
{
    case STATUS_101 = 'Pending';
    case STATUS_34 = 'Completed';
    case STATUS_22 = 'On hold';
}

And then call it with your fillable status something like "STATUS_" + $fillable.status


If not using Laravel 9, you may try as below described in : https://stackoverflow.com/a/55298089/2086966

class MyClass {
  const DEFAULT = 'default';
  const SOCIAL = 'social';
  const WHATEVER = 'whatever';
  public static $types = [self::DEFAULT, self::SOCIAL, self::WHATEVER];

and then write the rule as:

'type' => Rule::in(MyClass::$types)