2

I'm trying to get Employee Name based on employee_id of Task model using attributes properties of Spatie/Activitylog activity_log table.

My model:

use LogsActivity;

    protected $fillable = ['id','employee_id', 'name', 'description'......];

    protected static $logAttributes = ['id','employee_id','name', 'description'......];

    protected static $logFillable = true;
    protected static $logUnguarded = true;

My controller:

    {
        $activity = Activity::orderBy('id', 'DESC')->paginate(15);

        return view('adminlte::home', ['activity' => $activity]);
    }

My blade:

@foreach($activity as $act)

  {{$act->changes['attributes']['employee_id']}}

@endforeach

Records saved in properties field:

{"attributes":{"id":170,"employee_id":"[\"1\",\"2\"]","name":"test","description":"test",......}}

Also, in my blade the result is:

|employee_id | name       | description| ...
|------------|------------|------------|--------
|["1","2"]   | test       | test       | ....

The question is, how to get Name field based on employee_id. For example in this case, Jon, David(not their IDs(["1","2"]). So, I want to get Names instead of IDs.

Thank you in advance.

apokryfos
  • 38,771
  • 9
  • 70
  • 114
Besart Haziri
  • 67
  • 1
  • 6

1 Answers1

0

I would fetch them from the database

1) create a list of ids and fetch them.

$employees = Employee::whereIn('id', $activity->pluck('employee_id')->flatten())
    ->get()
    ->mapWithKeys(function ($employee) {
        return [$employee->id => $employee];
    });

2) Send it to the front-end

return view('adminlte::home', ['activity' => $activity, 'employees' => $employees]);

3) Use the mapping to display names

@foreach($activity as $act)
     @foreach($act->changes['attributes']['employee_id'] as $employeeId)
          {{ $employees[$employeeId] }}, 
     @endforeach
@endforeach
Ken
  • 2,654
  • 3
  • 26
  • 29