Laravel-activitylog: Want to log all attributes |聽protected static $logAttributes = [];

Created on 21 Sep 2016  路  2Comments  路  Source: spatie/laravel-activitylog

Hello, thanks for your great package.

Do you have a solution, when I want the crazy need to log all attributes.
I want to use LogsActivity in a BaseModel that is implemented by all Models.

namespace App\Models;

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

class BaseModel extends Model
{
    use LogsActivity;

    // HERE I WANT ALL ATTRIBUTES TO LOG FOR ALL CHILDREN MODELS
    protected static $logAttributes = [];

    // IN COMBINATION WITH THIS, IT'S COOL
    protected static $ignoreChangedAttributes = ['password'];
}

Seems to be crazy, but could be good for very large projects, where you don't want to touch all 200 and more models :-)

Most helpful comment

Under the hood, the $logAttributes property is used by the attributesToBeLogged() method, which returns an array. You could simply not set $logAttributes, and override the method instead:

public function attributesToBeLogged(): array
{
    return Schema::getColumnListing((new static)->getTable());
}

https://github.com/spatie/laravel-activitylog/blob/master/src/Traits/DetectsChanges.php#L25

All 2 comments

Here is my solution for it. Maybe it could be better. But I will share.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Schema;
use Spatie\Activitylog\Traits\LogsActivity;

class BaseModel extends Model
{

    use LogsActivity;

    protected static $logAttributes = [];

    protected static $ignoreChangedAttributes = ['password', 'remember_token'];

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            $attributes = Schema::getColumnListing($model->getTable());
            self::$logAttributes = $attributes;
        });

        static::updating(function ($model) {
            $attributes = Schema::getColumnListing($model->getTable());
            self::$logAttributes = $attributes;
        });

        static::deleting(function ($model) {
            $attributes = Schema::getColumnListing($model->getTable());
            self::$logAttributes = $attributes;
        });
    }
}

Under the hood, the $logAttributes property is used by the attributesToBeLogged() method, which returns an array. You could simply not set $logAttributes, and override the method instead:

public function attributesToBeLogged(): array
{
    return Schema::getColumnListing((new static)->getTable());
}

https://github.com/spatie/laravel-activitylog/blob/master/src/Traits/DetectsChanges.php#L25

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ianrussel picture ianrussel  路  5Comments

hackel picture hackel  路  5Comments

BerendSpigt picture BerendSpigt  路  4Comments

ekandreas picture ekandreas  路  3Comments

lflucasferreira picture lflucasferreira  路  3Comments