Laravel 12 - Spatie Activity Log
Laravel 12 - Spatie Activity Log
In this tutorial, we will learn how to track user activities in Laravel 12 using the Spatie Activity Log package, including logging user registrations and displaying them in a clean, readable format.
If you're a video person, feel free to skip the post and check out the video instead!
Quick Overview
In this guide, you’ll learn how to use the Spatie Laravel Activity Log package to track user actions, specifically, when a new user registers. Starting with a fresh Laravel project set up with Livewire Auth, you’ll install and configure the activity log package, publish the necessary files, and run migrations. You'll then update the registration logic to log activity automatically. To wrap it up, a simple route and view are added to display these logs in a clean, readable table making it easy to review user registration activity directly within your app.
Step # 1 : Set Up a New Laravel 12 Project with Livewire Auth.
To get started, create a new Laravel 12 project. If Laravel is installed globally use the following command.
laravel new activity-log
if you don’t have Laravel installed globally. Use Composer.
composer create-project laravel/laravel --prefer-dist activity-log
During setup, you’ll be prompted with configuration options. Choose the following.
- Would you like to install the starter kit? Select Livewire to enable Laravel's default Livewire-based frontend scaffolding.
- Which authentication provider do you prefer? Choose Laravel to use Laravel’s built-in authentication system.
- Would you like to use Laravel Volt? (yes/no) Type no, as we’re keeping things minimal without Volt.
- Which testing framework do you prefer? Select Pest, a modern and expressive testing framework for Laravel.
- Would you like to run npm install and npm run build? Type yes to automatically install frontend dependencies and compile assets.
It gives you a clean Laravel 12 project powered by Livewire and built-in auth, without the overhead of Volt. This lightweight configuration is ideal for adding features like an activity log with minimal friction.
Step # 2 : Navigate to Your Project.
Open your terminal and move into your Laravel project directory. For example.
cd c:xampp/htdocs/activity-log
Make sure you're in the root folder where your Laravel project is set up.
Step # 3 : Install the Activity Log Package.
To start logging user actions, install the spatie/laravel-activitylog package with Composer.
composer require spatie/laravel-activitylog
This package makes it easy to track events like registrations, logins, or any custom actions within your Laravel app.
Step # 4 : Publish Configuration and Migrations.
To get started with Laravel Activity Log, publish the configuration and migration files using these commands.
php artisan vendor:publish --provider="Spatie\Activitylog\ActivitylogServiceProvider" --tag="activitylog-config"
php artisan vendor:publish --provider="Spatie\Activitylog\ActivitylogServiceProvider" --tag="activitylog-migrations"
The first command publishes the config file so you can tweak the package settings. The second one provides the migration files needed to create the tables for storing activity logs.
Step # 5 : Run the Migrations.
Run the following command to apply the migrations and create the necessary database tables, including the activity_log table used for tracking logs.
php artisan migrate
Once done, your database will be ready to store user activity records.
Step # 6 : Log User Registration Activity.
Update the Register.php Livewire component to log user registrations using the activity() helper. Also, add a showRegistrationLogs() method to fetch and display the registration logs. This setup ensures that each new user registration is recorded with useful metadata, making it easier to track user activity later.
<?php
namespace App\Livewire\Auth;
use App\Models\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;
use Livewire\Attributes\Layout;
use Livewire\Component;
use Spatie\Activitylog\Models\Activity;
#[Layout('components.layouts.auth')]
class Register extends Component
{
public string $name = '';
public string $email = '';
public string $password = '';
public string $password_confirmation = '';
/**
* Handle an incoming registration request.
*/
public function register(): void
{
$validated = $this->validate([
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
'password' => ['required', 'string', 'confirmed', Rules\Password::defaults()],
]);
$validated['password'] = Hash::make($validated['password']);
event(new Registered(($user = User::create($validated))));
Auth::login($user);
// Log the activity
activity()
->causedBy($user)
->withProperties(['email' => $user->email])
->log("User {$user->name} created an account.");
$this->redirect(route('dashboard', absolute: false), navigate: true);
}
public function showRegistrationLogs()
{
// Get registration-related activities
$activities = Activity::where('description', 'like', 'User%created an account.')
->latest()
->get();
return view('logs', compact('activities'));
}
}
This logs each user registration along with their email, and adds a method to fetch and display these logs when needed.
Step # 7 : Define the Route to Display Logs.
Import the Register Livewire component and define a route to display user registration logs.
use App\Livewire\Auth\Register;
Route::get('/logs', [Register::class, 'showRegistrationLogs'])->middleware(['auth']);
This route loads the registration activity logs and is protected by the auth middleware, ensuring that only logged-in users can access it.
Step # 8 : Create a View to Display Registration Logs.
Create a new file named logs.blade.php inside the resources/views directory. Then, paste the following code into it 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-neutral-900 min-h-screen flex items-center justify-center p-6 text-white">
<div class="bg-neutral-800 border border-neutral-700 shadow-2xl rounded-xl p-8 w-full max-w-5xl">
<h1 class="text-3xl font-bold text-white mb-8 text-center">Registration Logs</h1>
<div class="overflow-x-auto">
<table class="min-w-full text-sm rounded-xl overflow-hidden">
<thead class="bg-neutral-700 text-neutral-200">
<tr>
<th class="px-6 py-3 text-left font-semibold">#</th>
<th class="px-6 py-3 text-left font-semibold">Description</th>
<th class="px-6 py-3 text-left font-semibold">Email</th>
<th class="px-6 py-3 text-left font-semibold">Date</th>
</tr>
</thead>
<tbody class="bg-neutral-800 divide-y divide-neutral-700">
@foreach ($activities as $index => $activity)
<tr class="hover:bg-neutral-700">
<td class="px-6 py-4">{{ $index + 1 }}</td>
<td class="px-6 py-4">{{ $activity->description }}</td>
<td class="px-6 py-4">{{ $activity->properties['email'] ?? 'N/A' }}</td>
<td class="px-6 py-4 text-neutral-400">
{{ $activity->created_at->format('d M Y, h:i A') }}
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
</body>
</html>
This view shows a clean, dark-themed table layout of user registration logs, including the description, email, and timestamp of each activity.
Step # 9 : See It in Action.
Start your Laravel development server.
php artisan serve
Now, register a new user from the registration page. Once done, head over to /logs in your browser. You should see a neatly formatted table showing the recent user registration activity.
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 integrated the Spatie Laravel Activity Log package into your Laravel 12 application to track user registration events. This setup offers a clean and effective way to capture and display important user actions, helping you monitor and audit behavior in your app. Thanks to the package’s flexibility, you can easily extend logging to cover other events beyond registration. Whether you're improving security, debugging issues, or tracking user behavior, activity logging adds valuable visibility to your Laravel project.
For further information, refer to the spatie/laravel-activitylog package documentation.
Share this with friends!
To engage in commentary, kindly proceed by logging in or registering
Subscribe to Our Newsletter
Stay ahead of the curve! Join our newsletter to see what everyone’s talking about.
0 Comments