Laravel 11 - Spatie Activity Log

Touseef Afridi
21 Jan 25

Laravel 11 - Spatie Activity Log

In this tutorial, learn how to integrate Spatie Activity Log in Laravel 11 to track user actions and changes. Discover its benefits for monitoring activities, ensuring security, and improving application insights.


If you're a video person, feel free to skip the post and check out the video instead!


Quick Overview

This guide walks you through integrating the Spatie Laravel Activity Log package to log user activities, such as user registration, in your Laravel project. After setting up a fresh Laravel project with Breeze Auth, you'll install the package, configure it, and create migrations for the activity log tables. Then, you'll modify the RegisteredUserController to log user registration events using the activity() helper method. A route and view are also created to display these logs. Finally, by running the development server, you'll test the feature and view the user registration logs in a user-friendly table.

Step # 1 : Create fresh Laravel project with Breeze Auth.

If you have Laravel installed globally, use the command.
laravel new activity-log
Or
if you don’t have Laravel installed globally. Use the Composer command.
composer create-project laravel/laravel --prefer-dist activity-log
After running one of these commands, you’ll be prompted with the following options.
  1. Would you like to install the starter kit? — Select Breeze
  2. After selecting Breeze, you'll be asked to choose your stack. — Select Blade
  3. After selecting Blade, you'll be asked for dark mode support. — Select no
  4. After selecting No, you'll be asked about testing framework. — Select Pest
  5. After selecting Pest, you'll be asked to select the database for your application. — Select mysql
  6. After selecting MySql, you'll be asked if you want to run the default database migration. — Select no

We’ll migrate all the tables together after setting up the activity log and other necessary tables.

Step # 2 : Access the project.

Open a terminal (e.g., Git Bash) and navigate to your Laravel project's root folder
cd c:xampp/htdocs/activity-log

Step # 3 : Install the Laravel Activity Log package.

To track user activities in your Laravel application, install the spatie/laravel-activitylog package via Composer.
composer require spatie/laravel-activitylog
This package allows you to log user actions and interactions in your Laravel app. It provides an easy way to track events like user registrations and other activities with relevant details.

Step # 4 : Publish Laravel Activity Log Configuration and Migrations.

To configure the activity log and set up necessary database tables, run the following commands.
php artisan vendor:publish --provider="Spatie\Activitylog\ActivitylogServiceProvider" --tag="activitylog-config"
php artisan vendor:publish --provider="Spatie\Activitylog\ActivitylogServiceProvider" --tag="activitylog-migrations"
These commands will publish the configuration file and migration files required for setting up the activity log in your Laravel project. The configuration file allows you to customize the behavior of the activity log, while the migration files will create the necessary database tables for storing logged activities.

Step # 5 : Run the Migration.

To create the necessary tables for the activity log, run the following command.
php artisan migrate
This will execute the migrations and set up the activity_log table and related tables in your database.

Step # 6 : Let's Log the User Registration Activity.

Update the RegisteredUserController as shown in the code below to log user registration activities using the activity() helper method. Additionally, create a showRegistrationLogs() method to retrieve and display the logged activities. The code tracks the registration action, logs the activity with user details, and provides a method to fetch and display the logged registration events.
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;
use Illuminate\View\View;
use Spatie\Activitylog\Models\Activity;
class RegisteredUserController extends Controller
{
    /**
     * Display the registration view.
     */
    public function create(): View
    {
        return view('auth.register');
    }
    /**
     * Handle an incoming registration request.
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
        ]);
        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);
        event(new Registered($user));
        Auth::login($user);
        // Log the activity
        activity()
        ->causedBy($user)
        ->withProperties(['email' => $user->email])
        ->log("User {$user->name} created an account.");
        return redirect(route('dashboard', absolute: false));
    }
    /**
    * Fetches and displays the latest user registration activities from the activity log.
    */
    public function showRegistrationLogs()
    {
    // Get registration-related activities
            $activities = Activity::where('description', 'like', 'User%created an account.')
            ->latest()
            ->get();
        return view('logs.registration', compact('activities'));
    }
}

Step # 7 : Create a route to retrieve the logs.

Import the RegisteredUserController and create a route to fetch the registration logs.
use App\Http\Controllers\Auth\RegisteredUserController;
Route::get('/log-registration', [RegisteredUserController::class, 'showRegistrationLogs'])->middleware(['auth']);
This route will fetch and display the user registration logs. Only authenticated users can access this route, as it is protected by the auth middleware.

Step # 8 : Create a view to display registration logs.

Create a logs folder in the resources/views directory, then create a registration.blade.php file inside it. Paste the following code to display the registration logs.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Code Shotcut - Registration Logs</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-900 min-h-screen flex flex-col items-center justify-center p-4">
    <div class="bg-white shadow-lg rounded-lg p-6 max-w-4xl w-full">
        <h1 class="text-2xl font-bold text-gray-800 mb-6 text-center">Registration Logs</h1>
        <div class="overflow-x-auto">
            <table class="min-w-full bg-white border border-gray-300 rounded-lg">
                <thead>
                    <tr class="bg-gray-200">
                        <th class="px-6 py-3 text-left text-sm font-medium text-gray-700 border-b">#</th>
                        <th class="px-6 py-3 text-left text-sm font-medium text-gray-700 border-b">Description</th>
                        <th class="px-6 py-3 text-left text-sm font-medium text-gray-700 border-b">Email</th>
                        <th class="px-6 py-3 text-left text-sm font-medium text-gray-700 border-b">Date</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-200">
                    @foreach ($activities as $index => $activity)
                        <tr>
                            <td class="px-6 py-4 text-sm text-gray-800">{{ $index + 1 }}</td>
                            <td class="px-6 py-4 text-sm text-gray-800">{{ $activity->description }}</td>
                            <td class="px-6 py-4 text-sm text-gray-800">{{ $activity->properties['email'] ?? 'N/A' }}</td>
                            <td class="px-6 py-4 text-sm text-gray-500">{{ $activity->created_at->format('d M Y, h:i A') }}</td>
                        </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
    </div>
</body>
</html>
This view will display a table with user registration logs, including descriptions, email addresses, and timestamps.

Step # 9 : It's time to test.

Start the Laravel development server.
php artisan serve
Create an account on the registration page, then visit the /log-registration route to view the log entry.

You should see a table displaying the logged user registration activities.

This example demonstrates how you can log specific activities such as user registration; however, you can customize it to log any activity based on your application's needs.

Conclusion

By following this guide, you’ve successfully integrated the Spatie Laravel Activity Log package to track user registration activities in your Laravel application. This solution provides a simple way to log and display significant user actions, making it easier to monitor and audit activity within your application. With the flexibility of the package, you can expand the logging to cover other important events. Whether for debugging, tracking user behavior, or enhancing application security, activity logging is a powerful tool for any Laravel project.
For further information, refer to the package documentation.
Share this with friends!


"Give this post some love and slap that 💖 button as if it owes you money! 💸😄"
0

0 Comments

To engage in commentary, kindly proceed by logging in or registering