Giter Club home page Giter Club logo

laravel-activitylog's Introduction

Social Card of Laravel Activity Log

Log activity inside your Laravel app

Latest Version on Packagist GitHub Workflow Status Check & fix styling Total Downloads

The spatie/laravel-activitylog package provides easy to use functions to log the activities of the users of your app. It can also automatically log model events. The Package stores all activity in the activity_log table.

Here's a demo of how you can use it:

activity()->log('Look, I logged something');

You can retrieve all activity using the Spatie\Activitylog\Models\Activity model.

Activity::all();

Here's a more advanced example:

activity()
   ->performedOn($anEloquentModel)
   ->causedBy($user)
   ->withProperties(['customProperty' => 'customValue'])
   ->log('Look, I logged something');

$lastLoggedActivity = Activity::all()->last();

$lastLoggedActivity->subject; //returns an instance of an eloquent model
$lastLoggedActivity->causer; //returns an instance of your user model
$lastLoggedActivity->getExtraProperty('customProperty'); //returns 'customValue'
$lastLoggedActivity->description; //returns 'Look, I logged something'

Here's an example on event logging.

$newsItem->name = 'updated name';
$newsItem->save();

//updating the newsItem will cause the logging of an activity
$activity = Activity::all()->last();

$activity->description; //returns 'updated'
$activity->subject; //returns the instance of NewsItem that was saved

Calling $activity->changes() will return this array:

[
   'attributes' => [
        'name' => 'updated name',
        'text' => 'Lorum',
    ],
    'old' => [
        'name' => 'original name',
        'text' => 'Lorum',
    ],
];

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Documentation

You'll find the documentation on https://spatie.be/docs/laravel-activitylog/introduction.

Find yourself stuck using the package? Found a bug? Do you have general questions or suggestions for improving the activity log? Feel free to create an issue on GitHub, we'll try to address it as soon as possible.

Installation

You can install the package via composer:

composer require spatie/laravel-activitylog

The package will automatically register itself.

You can publish the migration with:

php artisan vendor:publish --provider="Spatie\Activitylog\ActivitylogServiceProvider" --tag="activitylog-migrations"

Note: The default migration assumes you are using integers for your model IDs. If you are using UUIDs, or some other format, adjust the format of the subject_id and causer_id fields in the published migration before continuing.

After publishing the migration you can create the activity_log table by running the migrations:

php artisan migrate

You can optionally publish the config file with:

php artisan vendor:publish --provider="Spatie\Activitylog\ActivitylogServiceProvider" --tag="activitylog-config"

Changelog

Please see CHANGELOG for more information about recent changes.

Upgrading

Please see UPGRADING for details.

Testing

composer test

Contributing

Please see CONTRIBUTING for details.

Security

If you've found a bug regarding security please mail [email protected] instead of using the issue tracker.

Credits

And a special thanks to Caneco for the logo and Ahmed Nagi for all the work he put in v4.

License

The MIT License (MIT). Please see License File for more information.

laravel-activitylog's People

Contributors

abdullahfaqeir avatar adrianmrn avatar akosalman avatar alexvanderbist avatar bradcis avatar chrisrhymes avatar dependabot[bot] avatar drbyte avatar eduarguz avatar freekmurze avatar github-actions[bot] avatar grantholle avatar gummibeer avatar laravel-shift avatar lemaur avatar mallardduck avatar miclf avatar mo7zayed avatar mvdnbrk avatar nagi1 avatar nielsvanpach avatar pacoorozco avatar patinthehat avatar ragingdave avatar reecem avatar rubenvanassche avatar sebastiandedeyne avatar sebastiansson avatar stevebauman avatar steveporter92 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laravel-activitylog's Issues

Compatibility with LTS (Laravel 5.1)

Does this package actually use any Laravel 5.2 features? I have just installed it in my Laravel LTS project by aliasing the version ("laravel/framework": "5.1.36 as 5.2.21") and in my limited testing it appears to be working. I would like to suggest maintaining LTS compatibility moving forward!

Including IP Address of the Causer

It would be a good feature specially when users are generally logging in from different places. And it would help with tracking as well.

Limiting detected model changes to defined attributes

I was hoping to prevent a log occurring on a model "updating" event if the change only happened to a particular attribute. For example, I have a datetime field in a user model that I don't want to log changes to, and therefore don't want an activitylog entry if the changes only happened to that field.

Defining the $logAttributes property determines what gets stored for a model, but I can't see if any comparison actually happens to see if anything has actually changed.

Is there currently a way to do this?

installing problem

i can't install this package in laravel 5.2 and php version 5.6.23

Could not find package spatie/laravel-activitylog at any version matching your PHP version 5.6.23.0

Error message: class 'Illuminate\Auth\Guard' does not have a method 'guard'

Hi, I'm running into this error message when attempting to log an activity:

call_user_func_array() expects parameter 1 to be a valid callback, class 'Illuminate\Auth\Guard' does not have a method 'guard'

And the call is something like:

activity($this->log)
                ->causedBy($this->user)
                ->performedOn($this->slot)
                ->log($this->description);

I'm on Laravel 5.1.33. I haven't implemented guards yet. We are using Json Web Tokens and are using Laravel as a web service. Any help is appreciated.

Possibility to pass custom value

Hello,

Thats awesome package! Thx

I have issue with some of my models. In some models I have name field but in some no.
Is any chance to pass custom value by default to this?

lets say: $name = $this->size->name;
and latter pass it to $logAttributes

use LogsActivity;

    protected static $logAttributes = ['name'];

    public function getDescriptionForEvent(string $eventName): string
    {
        return "This target has been {$eventName}";
    }
public function size()
    {
        return $this->belongsTo('App\Models\Size');
    }

Thank you for answer.

How to disable logging when migrating

Hello,

I'm running artisan migrate:reset on my app before seeding new data for testing. Problem is that the package tries to log even when the activity_log table has been deleted.

Any way around that? Or should I make pull request with the solution?

Best wishes,
Siim

Custom properties documentation appears to be wrong

Possibly a bug, but maybe just a discrepancy in the documentation. Currently in 1.7, if I log with the following line from documentation:

activity()
   ->performedOn($anEloquentModel)
   ->causedBy($user)
   ->withProperties(['customProperty' => 'customValue'])
   ->log('Look mum, I logged something');

and then try to access it with the recommended syntax:

$lastLoggedActivity = Activity::all()->last();
$lastLoggedActivity->property('customProperty');

I get an error, even though calls like ->description work fine:

Call to undefined method Illuminate\Database\Query\Builder::property()

The only way I am able to access the custom properties is like this:

$lastLoggedActivity->properties['customProperty'];

This works fine for me, but I just wanted to make sure that's correct or if the documented method should be the correct way.

Do not log unchanged attributes

$activity->changes should only return attributes that changes and listed in $logAttributes.

Maybe by utilize Eloquent getDirty() method when saving logs.

Get log for specific causer

Hey,

any chance you could add a method to the Activity model so that only logs for a specific causer are retrieved? May even with another one for the current user only?

I know I can extend it, but I would think this could be a pretty useful thing that other people might use as well.

vendor:publish commands produce no change

I have just installed the package via composer and added it to the config/app.php file as Spatie\Activitylog\ActivitylogServiceProvider::class
In running the commands for publishing the migrations and tags, I get told "nothing to publish for tag [migrations] / tag [config]
Commands I ran:
php artisan vendor:publish --provider="Spatie\Activitylog\ActivitylogServiceProvider" --tag="migrations"
php artisan vendor:publish --provider="Spatie\Activitylog\ActivitylogServiceProvider" --tag="config"

I confirmed that the package is in the vendor folder where expected. Just not sure why these aren't working. I'm not sure how to troubleshoot this, so any help would be appreciated!

Does this package log relationship changes?

Hi,

I have recently been working on a more basic version of this package that is designed to log administrator activity. I have been having trouble working out an automatic way of logging changes to relationships (for example deleting a many-to-many relationship),

Have you found a way round this or are you not currently logging this information?

Thanks

Returning attributes

Hi,

When i do {{ $activity->changes }} in blade, it returns: ['attributes' => ['name' => 'original name', 'text' => 'Lorum']],

But how can i return just the name?

Delete event not Logged on 1.6 version

I ran the command "composer update" and "laravel-activitylog" updated to version 1.6.0
The event recording the record deletion log was not executed, the record was deleted from the Model table, but was not included in the "activity_log" table.

Want to log all attributes | protected static $logAttributes = [];

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 :-)

Log only dirty fields

Really nice package! Is there a way to log only dirty fields?
Currently I have to do a small hack like so:

protected static $logAttributes = [];     

public static function boot()
{
    parent::boot();
    static::saving(function (Model $model) {
        static::$logAttributes = array_keys($model->getDirty());
    });
}

Would be nice to have something baked in.

Have a custom log_name on Logging Model Events

Is it possible to have custom log_name on Logging Model Events?

Currently, on activity(), I can pass in custom log_name, but how can I have a custom log_name on Model that using Spatie\Activitylog\Traits\LogsActivity trait?

Probably something similar like getDescriptionForEvent?

Activity Model and Laravel Aliases/Facades

While working on backporting the code to PHP 5.6.
I noticed some inconsistencies with the use of the Activity model. While the user is able to define a custom 'activity_model' in the config file this information is not used by all of the laravel-activitylog classes. Instead, they default to the base Activity class. While this will work in most situations it makes it impossible for a user to reliably override any of the Activity class methods.

Additionally, I couldn't help but noticing that the common practice of using Laravel Aliases/Facades for the Activity class was abandoned. A feature that many end-users have become accustom to and reliant upon.

I have forked dev-master and made changes that resolve the Activity class inheritance issue and also adds the feature of the Activity alias.
https://github.com/CrashSensei/laravel-activitylog

Parse error: syntax error

Hi there,

I was trying to install package which installs perfectly fine without errors, but than afterwards getting a parse error as I refresh the page.
Parse error: syntax error, unexpected ':', expecting '{' in /var/www/localhost/api/vendor/spatie/laravel-activitylog/src/helpers.php on line 6

Am I the only one getting this error?

log() method returning $this

I'm curious why the log() method returns $this instead of the newly created Activity item?

Thanks for helping me understand!

Cartalyst Sentinel compatibility

I've problem in model logging when using sentinel as my auth manager.
I have to modify default ActivityLogger constructor to use Sentinel instead of AuthManager
Everything work fine for now.
IMHO it's better to add an config option for auth manager

sorry for my bad english.

Not loging properties

Hello,

Have issue with loging properties
Thats simple test in my controller.

$target = Target::find($id);
        //dd($target->size->name);
        activity()
            ->performedOn($target)
            ->withProperties(['customProperty' => 'customValue']);
        $target->delete();

To the database it records empty array. Where is my mistake?

I get syntax error when run my app ( unexpected ':', expecting '{' ) in helpers.php on line 6

While trying to execute my app, after laravel-activitylog properly installed and configured, got this error:

( ! ) Parse error: syntax error, unexpected ':', expecting '{' in /home/vagrant/Code/laravel-app/vendor/spatie/laravel-activitylog/src/helpers.php on line 6

The helper file has this content:
`<?php

use Spatie\Activitylog\ActivityLogger;

if (! function_exists('activity')) {
function activity(string $logName = null): ActivityLogger
{
$defaultLogName = config('laravel-activitylog.default_log_name');

    return app(ActivityLogger::class)->useLog($logName ?? $defaultLogName);
}

}`

What can i do in order to solve this problem ?

Atte., R. Steve Young.

Parse error expecting '{' in

Hi there,

I'm getting this error message when I do php artisan config:clear:

Parse error: parse error, expecting '{' in /Users/stijn/www/Sites/inventory/vendor/spatie/laravel-activitylog/src/helpers.php on line 6

Does anyone know what's wrong?

Thanks,
Stijn

This package requires PHP ^7.0, isn't too much updated requirement?

Hi, when I try to use this package on a PHP 5.6.5 box, composer throws:

Your requirements could not be resolved to an installable set of packages.
Problem 1

- Installation request for spatie/laravel-activitylog 1.7.1 -> satisfiable by spatie/laravel-activitylog[1.7.1].
- spatie/laravel-activitylog 1.7.1 requires php ^7.0 -> your PHP version (5.6.5) does not satisfy that requirement.

I think this is a very strong requirement. Is there any version for PHP 5.6?

Thanks in advance.

Authomatic log not working on update event

Activity log automatic model log on work on create but update and delete not being log. Example

namespace App\Models;

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

class BankModel extends Model
{
use LogsActivity;
//
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'tpoly_banks';
protected static $logAttributes = ['NAME', 'ACCOUNT_NUMBER'];
protected $primaryKey="ID";
protected $fillable=array ('NAME','ACCOUNT_NUMBER');

}

Add CausesActivity to docs

Hey, I did not find the CausesActivity trait in the docs, but I think it would be very helpful to mention it there.

How to set causer globally?

I'm using the activity logger for both web and api use, which means I have two log names. That all works fine. The problem is, the API user is using another guard, so it doesn't get picked up by the activity logger.

Is there a way to change the causer dynamically? I'm using automatic model logging through the LogsActivity trait.

Basically it's a matter of auth()->user() vs auth()->guard('api')->user().

Adding a custom Type field to records

Good morning - I'm attempting to add a type field to the activity_log table and would like to pass a value to it like this:

activity() ->ofType('item.added') ->log('Item added!');

I've set up my own custom model which extends \Spatie\Activitylog\Models\Activity and specified it be used in the config.

However, the activity() helper automatically loads up the ActivityLogger model, instead of mine, which means that I can't implement the ofType() method... unless I'm misunderstanding how to implement this.

Thanks for your thoughts and work on this package!

TypeError in DetectsChanges Trait on Model update

When I try to do an update of a model that is using the LogsActivity Trait, I get the following error:

Type error: Argument 1 passed to App\Address::logChanges() must be an instance of Illuminate\Database\Eloquent\Model, null given, called in C:\Web\my-app\vendor\spatie\laravel-activitylog\src\Traits\DetectsChanges.php on line 20

Here is the line in question:

$oldValues = $model->replicate()->setRawAttributes($model->getOriginal());

When I break that line into two, it works:

$oldValues = $model->replicate();
$oldValues->setRawAttributes($model->getOriginal());

Any thoughts?

As far as I can tell, the Eloquent Model function setRawAttributes says it returns $this, but it seems to be returning null instead.

PHP Version: reproducible on both 7.0.2 and 7.0.9
Laravel Version: Officially 5.2.x-dev 29ba2e3 in composer, which is same as 5.2.41
Laravel-ActivityLog Version: 1.2.1

Complete code of Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Phaza\LaravelPostgis\Eloquent\PostgisTrait;
use Spatie\Activitylog\Traits\LogsActivity;

class Address extends Model
{

    use PostgisTrait, LogsActivity;

    protected $postgisFields = ['location',];

    protected $fillable = [
        'street_address1',
        'street_address2',
        'city',
        'state',
        'country',
        'zipcode',
        'location',
    ];

}

Add SubjectOfActivity trait

Hey @freekmurze ,

what do you think of another trait SubjectOfActivity. It would basically be the opposite of the CausesActivity.

However we would need to find a good name for the relationship, as activity can not be used, as the causer model might also be the subject model in some cases.

Maybe also subjectOfActivity? Or maybe you have a better idea?

Warning: 1265 Data truncated for column 'causer_id'

Hi, I want try use this package. After installation and run a migration I try simple logging like at example

activity()->log('Look mum, I logged something'); But it always return me this error:

untitled

Any additional step to prevent this error?

Thanks

Single model that CausesActivity and LogsActivity

On my User model, I was using both the CausesActivity and LogsActivity traits, and now with 1.1.0 there is a conflict because the activity() method was added to both traits. What is the best way to achieve this? For now I've simply added LogsActivity::activity insteadof CausesActivity to my class, but I feel like this isn't ideal nor semantically appropriate.

The use case is simple: A User causes activities, but a user can also edit other users, and I want those activities to be logged.

(I realise these particular traits aren't all that complicated, but I could see them growing in the future.)

[Question]

Hi,

Love the package, good job guys!
Wouldn't it be a good idea to have the option to automatically add all attributes, without the need to specify all of them manually?

Kind regards

[doubt] Override implications

Does the updating static method override implementation below, cause the inability to attach other logic to the updating event of the model (from outside the trait, e.g. from another module)?

 static::updating(function (Model $model) {
                //temporary hold the original attributes on the model
                //as we'll need these in the updating event
                $oldValues = $model->replicate()->setRawAttributes($model->getOriginal());
                $model->oldAttributes = static::logChanges($oldValues);
            });

It is a better way to do that, isn't it?
What do you think about?

activitylog:clean

Command php artisan activitylog:clean not working.
I have records in table activity_log

Artisan returns:
Cleaning activity log...
Deleted 0 record(s) from the activity log.
All done!

multilingual?

hello

it is possible to use multilingual so that users see the activities in their own language?

best regards Martin

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.