How to Create Activity Logs in Laravel 11

Hello, laravel web developer! In this article, we'll see how to create activity logs in laravel 11. In laravel 11 we'll learn user activity logs. When the user performs any actions it will log on the database. So, it will be easy to identify events performed by users.

Here, we'll use spatie/laravel-activitylog package. It will automatically log model events. The Package stores all activity in the activity_log table.

Laravel 11 User Activity Logs using spatie/laravel-activitylog

Laravel 11 Activity Logs

 

 Step 1: Install Laravel 11 Application

If you haven't installed Laravel 11, use the following command to create a new Laravel 11 project:

composer create-project --prefer-dist laravel/laravel laravel-11-activity-logs

 

Step 2: Install and Setup

Then, we'll install spatie/laravel-activitylog composer package using the following command.

composer require spatie/laravel-activitylog

The package will automatically register the service provider

If you want to publish the migration with the following command.

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

After the migration has been published 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"

This is the contents of the published config file:

return [

    /*
     * If set to false, no activities will be saved to the database.
     */
    'enabled' => env('ACTIVITY_LOGGER_ENABLED', true),

    /*
     * When the clean-command is executed, all recording activities older than
     * the number of days specified here will be deleted.
     */
    'delete_records_older_than_days' => 365,

    /*
     * If no log name is passed to the activity() helper
     * we use this default log name.
     */
    'default_log_name' => 'default',

    /*
     * You can specify an auth driver here that gets user models.
     * If this is null we'll use the default Laravel auth driver.
     */
    'default_auth_driver' => null,

    /*
     * If set to true, the subject returns soft deleted models.
     */
    'subject_returns_soft_deleted_models' => false,

    /*
     * This model will be used to log activity.
     * It should be implements the Spatie\Activitylog\Contracts\Activity interface
     * and extend Illuminate\Database\Eloquent\Model.
     */
    'activity_model' => \Spatie\Activitylog\Models\Activity::class,

    /*
     * This is the name of the table that will be created by the migration and
     * used by the Activity model shipped with this package.
     */
    'table_name' => 'activity_log',
];

 

Step 3: Create a Controller

Next, we'll create an ActivityController.php file and define logic for activity logs.

php artisan make:controller ActivityController

app/Http/Controllers/ActivityController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use Spatie\Activitylog\Models\Activity;
  
class ActivityController extends Controller
{    
    public function Create(Request $request)
    {
        $user = new User();
        $user->name = $request->name;
        $user->email = $request->email;
        $user->save();
        
        activity('create')
        ->performedOn($user) // Entry add in table. model name(subject_type) & id(subject_id)
        ->causedBy(Auth::user()) //causer_id = admin id, causer type = admin model
        ->log('User Created By ' . Auth::user()->name);

        return redirect()->route('user-index')->with('success', "User Create Successfully");          
    }

    public function activityLogsList()
  	{
    	$activity_logs = Activity::with('causer')->get();
        return view('activity-logs', compact('activity_logs'));
    }
}

You can set who or what caused the activity by using causedBy()

If you're not using causedBy() the package will automatically use the logged in user.

 

Step 4: Custom Properties

You can add any property you want to an activity by using withProperties()

Setting custom properties

activity()
   ->causedBy($userModel)
   ->performedOn($someContentModel)
   ->withProperties(['key' => 'value'])
   ->log('edited');

$lastActivity = Activity::all()->last(); //returns the last logged activity

$lastActivity->getExtraProperty('key'); //returns 'value'

$lastActivity->where('properties->key', 'value')->get(); // get all activity where the `key` custom property is 'value'

 

Cleaning up the log

After using the package for a while you might have recorded a lot of activity. This package provides an artisan command activitylog:clean to clean the log.

php artisan activitylog:clean
$schedule->command('activitylog:clean')->daily();

 

Clean Records with Days

You can define the days to keep for each call as a command option.

php artisan activitylog:clean --days=7

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS