Laravel-activitylog: User username or name instead of user id

Created on 29 Nov 2016  路  5Comments  路  Source: spatie/laravel-activitylog

Hi I would like to say Thank You for this amazing Laravel Package.

My question is, how to use activity logger to save username instead of user id?

I am using this in model

use SpatieActivitylogTraitsLogsActivity;

class mymodel ectends model

use LogsActivity;
protected $causedBy = Auth::user()->name;
rotected static $logAttributes =["some"];

Most helpful comment

@ianrussel Yes, I showed you how to do that. If you aren't using name as your primary key, there's no way to do what you want, but I'm not really sure why you would want to. You can just do, e.g.:

Activity::with('causer')->get()->map(function ($m) {return $m->causer->name;});

You could also do this on your model:

    public $appends = ['name'];

    public function getNameAttribute()
    {
        return $this->causer->name ?? null;
    }

Then Activity::with('causer')->get()->toArray() will include the name field in the results automatically.

All 5 comments

I'm not quite sure what you're trying to do. You can't set a class property to a function like that.

The model's primary key is always used as the causer_id. This is how Laravel's MorphTo relationship works. Is "name" actually the primary key of your model? You can set it like this (assuming your DB is also set up this way):
protected $primaryKey = 'name';
Then, laravel-activitylog will use the name field as causer_id instead of id. Make sure you have also modified the migration for the activity_log table.

Hi Hackel, I am pertaining to causer_id field in activity log table in database. This will log the the user id of the current user.I want to save username or name instead of id.

Ian

@ianrussel Yes, I showed you how to do that. If you aren't using name as your primary key, there's no way to do what you want, but I'm not really sure why you would want to. You can just do, e.g.:

Activity::with('causer')->get()->map(function ($m) {return $m->causer->name;});

You could also do this on your model:

    public $appends = ['name'];

    public function getNameAttribute()
    {
        return $this->causer->name ?? null;
    }

Then Activity::with('causer')->get()->toArray() will include the name field in the results automatically.

@hackel Thank you.This work like a charm..

cheers!

ian

@ianrussel how did you solved it ? I'm into a project and I need to create a user activity feed and when i'm trying to display the user's name who did the action it shows nothing

Was this page helpful?
0 / 5 - 0 ratings

Related issues

DjKhireddine picture DjKhireddine  路  5Comments

abdosaeedelhassan picture abdosaeedelhassan  路  4Comments

federico-arona picture federico-arona  路  5Comments

rjcrystal picture rjcrystal  路  5Comments

TheFrankman picture TheFrankman  路  5Comments