Laravel Trustup Model History is a package designed to store and track changes made to Laravel models. It keeps a detailed history of modifications, helping developers audit changes, debug issues, or monitor how data evolves over time. This package allows you to track which attributes were changed, who made the changes, and when they occurred.
Key Features:
- Tracks Model Changes: Automatically logs any updates, creations, or deletions of models.
- Stores Old and New Values: Keeps a record of the previous and updated values of model attributes.
- User Identification: Tracks which user made the change if available.
- Customizable: You can configure which models and attributes to track and store in the history.
Installation
To install and use Laravel Trustup Model History, follow these steps:
- Require the Package: First, add the package to your project via Composer:
1composer require deegitalbe/laravel-trustup-model-history - Publish the Configuration and Migrations: After installing the package, publish its configuration and migration files:
12php artisan vendor:publish --provider="Deegitalbe\LaravelTrustupModelHistory\LaravelTrustupModelHistoryServiceProvider"php artisan migrate
This will create the necessary configuration file and database migration for storing model history. - Configure the Package: The published configuration file allows you to define how the package should behave. You can configure which models to track, which attributes to include or exclude, and more.The configuration file will be available at
config/trustup-model-history.php
.
Usage
To track changes on a model, simply use the TrackChanges
trait provided by the package.
- Add the Trait to Your Models: Open the model(s) you want to track and add the
TrackChanges
trait:
123456789101112namespace App\Models;use Deegitalbe\LaravelTrustupModelHistory\Traits\TrackChanges;use Illuminate\Database\Eloquent\Model;class Post extends Model{use TrackChanges;// Define fillable attributesprotected $fillable = ['title', 'content', 'author_id'];} - Track Specific Actions: By default, the package will track
create
,update
, anddelete
actions. If you want to track additional or custom actions, you can do so by customizing the package configuration.
Storing History Data
When a model is created, updated, or deleted, the package will automatically store a record of the change in the model_history
table. This table contains:
- Model name: The name of the model being tracked.
- Model ID: The ID of the model that was changed.
- Changes: The details of the attributes that were modified, including old and new values.
- User: Optionally, the ID of the user who made the change.
- Timestamp: The date and time the change occurred.
Retrieving History
You can easily retrieve the history of changes for any model. For example, if you want to get the history of changes made to a Post
model:
1 2 3 4 5 6 7 8 9 10 11 |
use App\Models\Post; $post = Post::find(1); $history = $post->history; // Retrieve change history foreach ($history as $change) { echo "Old Title: " . $change->old['title'] . "<br>"; echo "New Title: " . $change->new['title'] . "<br>"; echo "Changed by User ID: " . $change->user_id . "<br>"; echo "Changed at: " . $change->created_at . "<br>"; } |
Customizing History Tracking
You can customize how model changes are tracked by adjusting the package configuration:
- Selectively Track Models: Only track history for specific models.
- Exclude Attributes: Prevent certain model attributes from being logged (e.g., passwords, tokens).
- Soft Deletes: Track when models are soft deleted (if your models use soft deletes).
Example configuration file (config/trustup-model-history.php
):
1 2 3 4 5 6 7 8 9 10 11 12 |
return [ 'models' => [ // Specify the models for which history will be tracked App\Models\Post::class, App\Models\User::class, ], 'excluded_attributes' => [ // Attributes that won't be tracked 'password', 'remember_token', ], ]; |
Displaying History in Views
If you want to show the history of changes on a page, you can pass the history
data to your Blade views:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// Controller public function show($id) { $post = Post::findOrFail($id); return view('post.show', ['post' => $post, 'history' => $post->history]); } // Blade View (post/show.blade.php) @foreach ($history as $change) <p>Changed on {{ $change->created_at }} by User ID: {{ $change->user_id }}</p> <p>Old Title: {{ $change->old['title'] }}</p> <p>New Title: {{ $change->new['title'] }}</p> @endforeach |
Conclusion
Laravel Trustup Model History provides a powerful way to keep track of changes to your models. It’s useful for auditing, debugging, and monitoring purposes in your Laravel applications.
Additional Considerations
- Documentation: For more detailed usage and advanced options, refer to the official Laravel Trustup Model History documentation.
- Webhooks: The package can be extended to trigger webhooks when model changes occur, useful for integrating with external services.
Output:
The Laravel Trustup Model History package operates behind the scenes by logging changes to the database rather than providing direct output like console logs. The output is stored in a database table and can be retrieved and displayed via a view or in a debugging console.
1. Database Table Logs
After changes are made to a tracked model (e.g., Post
), the changes are recorded in the model_history
table in the database. You can inspect this table using tools like phpMyAdmin, Sequel Pro, or Laravel Tinker.
Example SQL query to inspect the changes:
1 |
SELECT * FROM model_history WHERE model_type = 'App\\Models\\Post'; |
This will show entries like:
- model_type:
App\Models\Post
- model_id:
1
(ID of the post that changed) - changes: JSON object of old and new values
- user_id: ID of the user who made the change
- created_at: Timestamp of when the change occurred
2. Display Output in Views
If you want to display the model change history in your application’s UI, you can pass the history
to a Blade view and show it.
Example Controller to Retrieve and Pass the History:
1 2 3 4 5 6 7 |
public function showHistory($id) { $post = App\Models\Post::findOrFail($id); $history = $post->history; // Retrieve the history of changes return view('post.history', compact('post', 'history')); } |
Example Blade View (resources/views/post/history.blade.php
):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<h1>Change History for Post: {{ $post->title }}</h1> <table border="1"> <thead> <tr> <th>Date</th> <th>Changed By</th> <th>Old Title</th> <th>New Title</th> </tr> </thead> <tbody> @foreach ($history as $change) <tr> <td>{{ $change->created_at }}</td> <td>User ID: {{ $change->user_id }}</td> <td>{{ $change->old['title'] ?? 'N/A' }}</td> <td>{{ $change->new['title'] ?? 'N/A' }}</td> </tr> @endforeach </tbody> </table> |
Expected Output in the Browser:
When a user visits the page, they would see something like:
Change History for Post: Laravel Trustup Model History
Date | Changed By | Old Title | New Title |
---|---|---|---|
2024-09-30 | User ID: 1 | Laravel Audit Feature | Laravel Trustup Model History |
2024-09-29 | User ID: 2 | Initial Post Title | Laravel Audit Feature |
3. Debug Output in Logs
You can also log the changes in Laravel’s log file using the Log
facade:
Example Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
use Illuminate\Support\Facades\Log; $post = App\Models\Post::find(1); $history = $post->history; foreach ($history as $change) { Log::info('Model changed:', [ 'old' => $change->old, 'new' => $change->new, 'user' => $change->user_id, 'time' => $change->created_at, ]); } |
Example Log Output (storage/logs/laravel.log
):
1 |
[2024-09-30 12:34:56] local.INFO: Model changed: {"old":{"title":"Laravel Audit Feature"},"new":{"title":"Laravel Trustup Model History"},"user":1,"time":"2024-09-30 12:34:56"} |
Summary of Outputs:
- Database Table: You can view the history in the
model_history
table. - Web View: Display history data in a Blade template.
- Logs: Log the changes in the
laravel.log
file for debugging.
- Laravel Breeze – Simple authentication starter kit
- Laravel Jetstream – Scaffolding for Laravel apps
- Laravel Passport – API authentication via OAuth2
- Laravel Sanctum – Simple API authentication
- Spatie Laravel Permission – Role and permission management
- Laravel Cashier – Subscription billing with Stripe
- Laravel Scout – Full-text search using Algolia
- Laravel Socialite – OAuth authentication (Google, Facebook, etc.)
- Laravel Excel – Excel import and export for Laravel
- Laravel Horizon – Redis queues monitoring
- Laravel Nova – Admin panel for Laravel
- Laravel Fortify – Backend authentication for Laravel
- Laravel Vapor – Serverless deployment on AWS
- Laravel Telescope – Debugging assistant for Laravel
- Laravel Dusk – Browser testing
- Laravel Mix – API for compiling assets
- Spatie Laravel Backup – Backup management
- Laravel Livewire – Building dynamic UIs
- Spatie Laravel Media Library – Manage media uploads
- Laravel Excel – Excel spreadsheet handling
- Laravel Debugbar – Debug tool for Laravel
- Laravel WebSockets – Real-time communication
- Spatie Laravel Sitemap – Generate sitemaps
- Laravel Spark – SaaS scaffolding
- Laravel Envoy – Task runner for deployment
- Spatie Laravel Translatable – Multilingual model support
- Laravel Backpack – Admin panel
- Laravel AdminLTE – Admin interface template
- Laravel Collective Forms & HTML – Simplified form and HTML generation
- Spatie Laravel Analytics – Google Analytics integration Advertisement
- Laravel Eloquent Sluggable – Automatically create slugs
- Laravel Charts – Chart integration
- Laravel Auditing – Track changes in models
- Laravel JWT Auth – JSON Web Token authentication
- Laravel Queue Monitor – Monitor job queues
- Spatie Laravel Query Builder – Filter, sort, and include relationships in Eloquent queries
- Laravel Datatables – jQuery Datatables API
- Laravel Localization – Multilingual support for views and routes
- Laravel Acl Manager – Access control list manager
- Laravel Activity Log – Record activity in your app
- Laravel Roles – Role-based access control
- Spatie Laravel Tags – Tagging models
- Laravel Installer – CLI installer for Laravel
- Laravel Breadcrumbs – Generate breadcrumbs in Laravel
- Laravel Mailgun – Mailgun integration for Laravel
- Laravel Trustup Model History – Store model change history
- Laravel Deployer – Deployment automation tool
- Laravel Auth – Custom authentication guards
- Laravel CORS – Cross-Origin Resource Sharing (CORS) support
- Laravel Notifications – Send notifications through multiple channels
- Spatie Laravel Http Logger – Log HTTP requests
- Laravel Permission Manager – Manage permissions easily
- Laravel Stubs – Customize default stubs in Laravel
- Laravel Fast Excel – Speed up Excel exports
- Laravel Image – Image processing
- Spatie Laravel Backup Server – Centralize backups for Laravel apps
- Laravel Forge API – Manage servers through the Forge API
- Laravel Blade SVG – Use SVGs in Blade templates
- Laravel Ban – Ban/unban users from your application
- Laravel API Response – Standardize API responses
- Laravel SEO – Manage SEO meta tags
- Laravel Settings – Store and retrieve settings
- Laravel DOMPDF – Generate PDFs
- Laravel Turbo – Full-stack framework for building modern web apps
- Spatie Laravel Event Sourcing – Event sourcing implementation
- Laravel Jetstream Inertia – Jetstream’s Inertia.js integration
- Laravel Envoy Tasks – Task automation
- Laravel Likeable – Like/dislike functionality
- Laravel GeoIP – Determine visitor’s geographic location
- Laravel Country State City – Dropdowns for country, state, and city
- Laravel Hashids – Generate short unique hashes
- Laravel Repository – Repository pattern for Laravel
- Laravel UUID – UUID generation for models
- Spatie Laravel Medialibrary Pro – Enhanced media management
- Laravel Queue Monitor – Monitor Laravel job queues
- Laravel User Activity – Monitor user activity
- Laravel DB Snapshots – Create database snapshots
- Laravel Twilio – Twilio integration
- Laravel Roles – Role-based permission handling
- Laravel Translatable – Add translations to Eloquent models
- Laravel Teamwork – Manage teams in multi-tenant apps
- Laravel Full Text Search – Add full-text search to Laravel models
- Laravel File Manager – File and media management
- Laravel User Timezones – Automatically detect user time zones
- Laravel ChartsJS – Render charts with ChartsJS
- Laravel Stripe – Stripe API integration
- Laravel PDF Generator – PDF generation
- Laravel Elasticsearch – Elasticsearch integration
- Laravel Simple Qrcode – Generate QR codes
- Laravel Timezone – Manage timezones and conversions
- Laravel Collective API – API management for Laravel
- Laravel Rest API Boilerplate – REST API starter kit
- Laravel Multi Auth – Multi-authentication functionality
- Laravel Voyager – Admin panel for Laravel
- Laravel Voyager Database – Database manager for Voyager
- Laravel Categories – Handle categories for models
- Laravel Multitenancy – Multi-tenancy implementation
- Laravel Access Control – Advanced access control for users
- Laravel Menus – Menu management
- Laravel Translatable Routes – Multilingual route handling