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 - 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.