almosabbirrakib / laravel-activity-log
A comprehensive Laravel package for logging user activities with support for Blade, Vue 2, and Vue 3 frontends
Installs: 10
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 0
Forks: 0
Open Issues: 0
pkg:composer/almosabbirrakib/laravel-activity-log
Requires
- php: ^8.0|^8.1|^8.2
- illuminate/database: ^9.0|^10.0|^11.0
- illuminate/http: ^9.0|^10.0|^11.0
- illuminate/support: ^9.0|^10.0|^11.0
Requires (Dev)
- orchestra/testbench: ^7.0|^8.0|^9.0
- phpunit/phpunit: ^9.5|^10.0
This package is auto-updated.
Last update: 2025-11-18 15:49:18 UTC
README
A comprehensive, production-ready Laravel package for logging and monitoring user activities with support for Blade, Vue 2, and Vue 3 frontends. Track every action in your application with a beautiful, professional dashboard.
โจ Features
- ๐ฏ Easy Integration - Simple trait-based implementation, ready in minutes
- ๐จ Multiple Frontend Options - Choose between Blade, Vue 2, or Vue 3 components
- ๐ Beautiful Dashboard - Professional UI with Tailwind CSS and responsive design
- ๐ Advanced Filtering - Search, filter by type, date range, user, and subject
- ๐ Statistics Dashboard - Real-time stats (total, today, this week, this month)
- ๐ High Performance - Optimized queries with proper database indexing
- ๐ Secure by Default - Configurable middleware, authentication, and sensitive data exclusion
- ๐ฆ Highly Configurable - Extensive configuration options with sensible defaults
- ๐งน Automatic Cleanup - Built-in Artisan command for log retention management
- ๐ญ Multiple Log Types - Created, updated, deleted, login, logout, and custom types
- ๐ RESTful API - Complete API endpoints for external integrations
- ๐ Polymorphic Relations - Track activities on any model
- ๐พ Flexible Storage - Store additional metadata as JSON properties
- ๐ ๏ธ Helper Functions - Convenient global helpers for quick logging
- ๐ฑ Mobile Responsive - Works perfectly on all screen sizes
๐ Requirements
- PHP: 8.0 or higher
- Laravel: 9.x, 10.x, or 11.x
- Database: MySQL 5.7+ / PostgreSQL 9.6+ / SQLite 3.8+
๐ Quick Start
Installation
# Install the package composer require almosabbirrakib/laravel-activity-log # Run the installation command php artisan activity-log:install # Run migrations php artisan migrate
Basic Usage
use AlMosabbirRakib\ActivityLog\Facades\ActivityLog; // Log a simple activity ActivityLog::log('User viewed dashboard'); // Log with type and properties ActivityLog::log('Settings updated', 'updated', [ 'theme' => 'dark', 'language' => 'en' ]); // Using helper functions activity_log('User performed action'); activity_login(); activity_logout();
Add to Your Models
use AlMosabbirRakib\ActivityLog\Traits\LogsActivity; class Post extends Model { use LogsActivity; } // Now all model events are automatically logged! $post = Post::create(['title' => 'My Post']); // Logged $post->update(['title' => 'Updated']); // Logged $post->delete(); // Logged
View Activity Logs
Visit the dashboard in your browser:
http://your-app.test/activity-logs
๐ Documentation
Table of Contents
- Installation Guide
- Configuration
- Usage Examples
- Frontend Integration
- API Endpoints
- Artisan Commands
- Advanced Usage
๐ง Configuration
After installation, configure the package in config/activity-log.php:
return [ // Database table name 'table_name' => 'activity_logs', // User model 'user_model' => 'App\\Models\\User', // Routes 'routes' => [ 'enabled' => true, 'prefix' => 'activity-logs', 'middleware' => ['web', 'auth'], 'api_middleware' => ['api', 'auth:sanctum'], ], // Pagination 'per_page' => 15, // Automatic logging 'auto_log' => [ 'enabled' => false, // Set to true to enable 'events' => ['created', 'updated', 'deleted'], ], // Log retention (null = keep forever) 'retention_days' => 90, // Privacy settings 'log_ip_address' => true, 'log_user_agent' => true, // Excluded attributes (won't be logged) 'excluded_attributes' => [ 'password', 'remember_token', 'api_token', ], ];
๐ก Usage
Using the Trait (Recommended)
Add the LogsActivity trait to any model:
use AlMosabbirRakib\ActivityLog\Traits\LogsActivity; class Post extends Model { use LogsActivity; }
Enable automatic logging in config:
'auto_log' => [ 'enabled' => true, 'events' => ['created', 'updated', 'deleted'], ],
Using the Facade
use AlMosabbirRakib\ActivityLog\Facades\ActivityLog; // Simple log ActivityLog::log('User viewed dashboard'); // With type ActivityLog::log('Report generated', 'export'); // With properties ActivityLog::log('Settings updated', 'updated', [ 'old_theme' => 'light', 'new_theme' => 'dark', ]); // With subject ActivityLog::log('Post published', 'published', [], $post); // Predefined methods ActivityLog::created($post); ActivityLog::updated($post, 'Post content updated'); ActivityLog::deleted($post); ActivityLog::login($user); ActivityLog::logout($user);
Using Helper Functions
// Simple logging activity_log('User performed action'); // Predefined helpers activity_created($post); activity_updated($post, 'Post updated'); activity_deleted($post); activity_login(); activity_logout();
Controller Examples
class PostController extends Controller { public function store(Request $request) { $post = Post::create($request->validated()); ActivityLog::created($post, 'New post created: ' . $post->title); return redirect()->route('posts.show', $post); } public function update(Request $request, Post $post) { $oldTitle = $post->title; $post->update($request->validated()); ActivityLog::updated($post, 'Post updated', [ 'old_title' => $oldTitle, 'new_title' => $post->title, ]); return redirect()->route('posts.show', $post); } }
Retrieving Logs
use AlMosabbirRakib\ActivityLog\Models\ActivityLog; // Get all logs $logs = ActivityLog::latest()->paginate(15); // Filter by type $createdLogs = ActivityLog::ofType('created')->get(); // Filter by user $userLogs = ActivityLog::forCauser($user)->get(); // Filter by subject $postLogs = ActivityLog::forSubject($post)->get(); // Date range $logs = ActivityLog::dateRange('2024-01-01', '2024-12-31')->get(); // Search $logs = ActivityLog::search('login')->get(); // Combined filters $logs = ActivityLog::ofType('updated') ->dateRange('2024-01-01', '2024-12-31') ->search('post') ->latest() ->paginate(20); // From model relationships $post = Post::find(1); $logs = $post->activityLogs; $user = User::find(1); $activities = $user->causedActivities;
๐จ Frontend Integration
Blade (Default)
The Blade view is automatically available at /activity-logs:
<!-- Include in your layout --> <a href="{{ route('activity-logs.index') }}">Activity Logs</a> <!-- Or embed directly --> @include('activity-log::index')
Vue 2 Integration
// In resources/js/app.js import Vue from 'vue'; import ActivityLogVue2 from './components/activity-log/ActivityLogVue2.vue'; Vue.component('activity-log', ActivityLogVue2); new Vue({ el: '#app', });
<!-- In your Blade template --> <div id="app"> <activity-log api-base-url="/api/activity-logs"></activity-log> </div>
Vue 3 Integration
// In resources/js/app.js import { createApp } from 'vue'; import ActivityLogVue3 from './components/activity-log/ActivityLogVue3.vue'; const app = createApp({ components: { ActivityLogVue3 } }); app.mount('#app');
<!-- In your template --> <template> <ActivityLogVue3 api-base-url="/api/activity-logs" /> </template>
๐ API Endpoints
All API endpoints are prefixed with /api/activity-logs:
Get All Logs
GET /api/activity-logs
Query Parameters:
page- Page number (default: 1)per_page- Items per page (default: 15)search- Search in descriptiontype- Filter by typedate_from- Start date (Y-m-d)date_to- End date (Y-m-d)causer_id- Filter by user IDcauser_type- Filter by user typesubject_id- Filter by subject IDsubject_type- Filter by subject type
Example:
curl -X GET "http://your-app.test/api/activity-logs?page=1&per_page=15&type=created&search=post" \ -H "Authorization: Bearer YOUR_TOKEN"
Get Single Log
GET /api/activity-logs/{id}
Get Log Types
GET /api/activity-logs/types
Get Statistics
GET /api/activity-logs/stats
Returns:
{
"total": 1250,
"today": 45,
"this_week": 320,
"this_month": 890
}
Cleanup Old Logs
DELETE /api/activity-logs/cleanup?days=90
๐ ๏ธ Artisan Commands
Install Package Assets
# Install all assets php artisan activity-log:install # Install specific assets php artisan activity-log:install --config php artisan activity-log:install --migrations php artisan activity-log:install --views php artisan activity-log:install --components # Force overwrite existing files php artisan activity-log:install --force
Clean Old Logs
# Interactive cleanup php artisan activity-log:clean # Clean logs older than 30 days php artisan activity-log:clean --days=30 # Force cleanup without confirmation php artisan activity-log:clean --days=90 --force
Scheduled Cleanup
Add to app/Console/Kernel.php:
protected function schedule(Schedule $schedule) { // Clean logs older than 90 days, daily at 2 AM $schedule->command('activity-log:clean --days=90 --force') ->dailyAt('02:00'); }
๐ฅ Advanced Usage
Custom Activity Descriptions
class Post extends Model { use LogsActivity; protected function getActivityDescription(string $type): string { return match ($type) { 'created' => "New post created: {$this->title}", 'updated' => "Post updated: {$this->title}", 'deleted' => "Post deleted: {$this->title}", default => parent::getActivityDescription($type), }; } }
Custom Activity Properties
class Post extends Model { use LogsActivity; protected function getActivityProperties(string $type): array { return [ 'title' => $this->title, 'category' => $this->category->name, 'author' => $this->author->name, 'status' => $this->status, ]; } }
Middleware for Automatic Request Logging
Add to app/Http/Kernel.php:
protected $middlewareGroups = [ 'web' => [ // ... other middleware \AlMosabbirRakib\ActivityLog\Middleware\LogActivity::class, ], ];
Or apply to specific routes:
Route::middleware(['auth', \AlMosabbirRakib\ActivityLog\Middleware\LogActivity::class]) ->group(function () { Route::resource('posts', PostController::class); });
E-commerce Example
// Order placed ActivityLog::log('Order placed', 'order_placed', [ 'order_id' => $order->id, 'total' => $order->total, 'items_count' => $order->items->count(), ], $order); // Payment processed ActivityLog::log('Payment processed', 'payment', [ 'amount' => $payment->amount, 'method' => $payment->method, 'transaction_id' => $payment->transaction_id, ], $payment);
๐ฏ Use Cases
- Audit Trails - Track all changes to critical data
- User Monitoring - Monitor user actions and behavior
- Security - Detect suspicious activities
- Compliance - Meet regulatory requirements (GDPR, HIPAA, etc.)
- Debugging - Trace issues and understand user flows
- Analytics - Analyze user behavior patterns
- Customer Support - Help users by reviewing their activity history
๐ Security
- Authentication Required - All routes protected by authentication middleware
- Sensitive Data Exclusion - Passwords and tokens automatically excluded
- Configurable Privacy - Control IP and user agent logging
- API Authentication - Laravel Sanctum support for API endpoints
- Customizable Middleware - Add your own authorization logic
โก Performance
- Optimized Queries - Proper database indexing on all searchable columns
- Eager Loading - Relationships loaded efficiently
- Pagination - Large datasets handled with pagination
- Configurable Retention - Automatic cleanup prevents database bloat
- Minimal Overhead - Lightweight implementation with no performance impact
๐งช Testing
# Run tests (coming soon) composer test
๐ Changelog
Please see CHANGELOG for more information on what has changed recently.
๐ค Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
๐ Security Vulnerabilities
If you discover a security vulnerability, please send an e-mail to Al Mosabbir Rakib via mrakib50.cse@gmail.com. All security vulnerabilities will be promptly addressed.
๐ License
The Laravel Activity Log package is open-sourced software licensed under the MIT license.
๐จโ๐ป Author
Al-Mosabbir Rakib
- GitHub: @almosabbirrakib
- Email: mrakib50.cse@gmail.com
๐ Acknowledgments
- Built with โค๏ธ for the Laravel community
- Inspired by the need for simple, beautiful activity logging
- Thanks to all contributors and users
Made with โค๏ธ by Al-Mosabbir Rakib
โญ If you find this package helpful, please consider giving it a star on GitHub! โญ