An audit trail is a record of all changes made to a data model. A model is any entity that can be stored in a database, such as a user or a product. An audit entry typically contains information about the type of change (creation, update, or deletion), made the change, and the change was made. Audit trails are often used in large applications where there is need to track changes to one or more models over time. who when In this tutorial, we’ll set up an audit trail dashboard accessible to admins for a simple stock application. Our dashboard will update in realtime, allowing us to see updates as they happen. Here’s a preview of our app in action: Prerequisites PHP 7.1.3 or higher Composer A Pusher account. Create one . here Setup We’ll start out with a small stock management application I built. You can clone the project from GitHub by running: git clone https://github.com/shalvah/stockt.git You can also download the source directly from this link. Then into the project folder and install dependencies: cd composer install Next, copy the to a new file called . Run the following command to generate an application encryption key: .env.example .env php artisan key:generate Lastly, create a file called in the directory and run the following command to set up and populate the database: database.sqlite database php artisan migrate --seed Creating the audit dashboard We’ll use the package to handle auditing. Let’s install the package: laravel-auditing composer require owen-it/laravel-auditing Next, we’ll publish the database migrations for the audit tables and run them: php artisan auditing:installphp artisan migrate We’re going to be auditing changes to products. Let’s configure our product model so the auditing package can track it. In your model ( ): Product app/Models/Product.php the trait use OwenIt\Auditing\Auditable the interface: implement OwenIt\Auditing\Contracts\Auditable <?php namespace App\\Models; use Illuminate\\Database\\Eloquent\\Model; use OwenIt\\Auditing\\Contracts\\Auditable; class Product extends Model implements Auditable { use \\OwenIt\\Auditing\\Auditable; // ... } Now, whenever a change is made to a product, the details of the change will be recorded in the table. audits We need to make a small change to our auditing configuration so the model can properly map to our model. This will enable us to write code like to retrieve the name of the user who made the change. In the file , replace the value of in the array with the class name of our User model ( ) Audit User $audit→user→name config/audit.php model user App\Models\User::class 'user' => ['primary_key' => 'id','foreign_key' => 'user_id', // replace the line below 'model' => App\\User::class, // with this 'model' => App\\Models\\User::class, \], Now, on to the audits dashboard. First, we’ll create a middleware that allows only admin users to view the page. Create a file called .php in with the following content: AllowOnlyAdmin app/Http/Middleware <?php namespace App\\Http\\Middleware; use Closure; use Illuminate\\Support\\Facades\\Auth; class AllowOnlyAdmin { public function handle($request, Closure $next) { if (Auth::user()->is\_admin) { return $next($request); } abort(403); } } Next, add the route for the audits at the end of your : routes/web.php Route::get('audits', 'AuditController@index')->middleware('auth', \App\Http\Middleware\AllowOnlyAdmin::class); Let’s create the controller. We’ll generate the file .php by running: app/Http/Controllers/AuditController php artisan make:controller AuditController Create an method within the class with the following content: index AuditController public function index(){$audits = \OwenIt\Auditing\Models\Audit::with('user')->orderBy('created_at', 'desc')->get();return view('audits', ['audits' => $audits]);} Let’s build the view for our audits. Create the file with the following content: resources/views/audits.blade.php ('layouts.app') @extends [@section](http://twitter.com/section "Twitter profile for @section")('content') <div class="container"> <table class="table" > <thead class="thead-dark"> <tr> <th scope="col">Model</th> <th scope="col">Action</th> <th scope="col">User</th> <th scope="col">Time</th> <th scope="col">Old Values</th> <th scope="col">New Values</th> </tr> </thead> <tbody id="audits"> [@foreach](http://twitter.com/foreach "Twitter profile for @foreach")($audits as $audit) <tr> <td>{{ $audit->auditable\_type }} (id: {{ $audit->auditable\_id }})</td> <td>{{ $audit->event }}</td> <td>{{ $audit->user->name }}</td> <td>{{ $audit->created\_at }}</td> <td> <table class="table"> [@foreach](http://twitter.com/foreach "Twitter profile for @foreach")($audit->old\_values as $attribute => $value) <tr> <td><b>{{ $attribute }}</b></td> <td>{{ $value }}</td> </tr> [@endforeach](http://twitter.com/endforeach "Twitter profile for @endforeach") </table> </td> <td> <table class="table"> [@foreach](http://twitter.com/foreach "Twitter profile for @foreach")($audit->new\_values as $attribute => $value) <tr> <td><b>{{ $attribute }}</b></td> <td>{{ $value }}</td> </tr> [@endforeach](http://twitter.com/endforeach "Twitter profile for @endforeach") </table> </td> </tr> [@endforeach](http://twitter.com/endforeach "Twitter profile for @endforeach") </tbody> </table> </div> [@endsection](http://twitter.com/endsection "Twitter profile for @endsection") You can start your app by running: php artisan serve Then visit your app on . The app comes with two default users: an admin user (Administrator, ), and a regular user (John Doe, ). (Both passwords: ) Sign in to your app as John Doe and as Administrator and make changes to some of the products displayed on the homepage. Then visit as Administrator to see the list of all changes made by all users. http://localhost:8000 stockt admin@stockt.test john@stockt.test secret http://localhost:8000/audits Displaying new audits in realtime Now we’ve got our audit dashboard working, but we need to reload the page whenever we wish to see any new changes. This is where our realtime functionality, powered by Pusher, comes in. Let’s implement it. First, we’ll set up Pusher on the backend. Install the Pusher Laravel package: composer require pusher/pusher-http-laravel php artisan vendor:publish --provider="Pusher\Laravel\PusherServiceProvider" Edit your so it looks like this: config/pusher.php 'connections' => ['main' => ['auth_key' => env('PUSHER_APP_KEY'),'secret' => env('PUSHER_APP_SECRET'),'app_id' => env('PUSHER_APP_ID'),'options' => ['cluster' => env('PUSHER_APP_CLUSTER'),],'host' => null,'port' => null,'timeout' => null,],], Sign in to and create a new app. Copy your app credentials from the section and add them to your file: your Pusher dashboard App Keys .env PUSHER_APP_ID=your-app-idPUSHER_APP_KEY=your-app-keyPUSHER_APP_SECRET=your-app-secretPUSHER_APP_CLUSTER=your-app-cluster Note: Laravel sometimes caches old configuration, so for the project to see your new configuration values, you might need to run the command _php artisan config:clear_ The package fires an event called whenever a new audit is created. We’ll listen for this event and trigger a event on Pusher. Our frontend will listen for this event and add the new audit item to the table. laravel-auditing Audited new-audit Create the event listener, with the following content: app/Listeners/AuditedListener.php <?php namespace App\\Listeners; use OwenIt\\Auditing\\Events\\Audited; use Pusher\\Laravel\\Facades\\Pusher; class AuditedListener { public function handle(Audited $event) { $audit = $event->audit->toArray(); $audit\['user\_name'\] = $event->audit->user->name; Pusher::trigger('audits', 'new-audit', \['audit' => $audit\]); } } Next, we’ll register the event listener in the : app/Providers/EventServiceProvider.php class EventServiceProvider extends ServiceProvider{protected $listen = [\OwenIt\Auditing\Events\Audited::class => [\App\Listeners\AuditedListener::class]]; // ... } Here’s the code we’ll use to handle the event. We pull in the library, subscribe to the channel and bind to the event. When an event comes in, we build up a new row and insert it at the top of the table. Add the code to the end of your : pusher-js audits new-audit resources/views/audits.blade.php <script src=" "></script><script>var socket = new Pusher("your-app-key", {cluster: 'your-app-cluster',});socket.subscribe('audits').bind('new-audit', function (data) {var audit = data.audit;var $modelCell = $('<td>').text(audit.auditable_type + '(id: ' + audit.auditable_id + ')');var $eventCell = $('<td>').text(audit.event);var $userCell = $('<td>').text(audit.user_name);var $timeCell = $('<td>').text(audit.created_at); https://js.pusher.com/4.2/pusher.min.js function createSubTable(values) { var $table = $('<table>').addClass('table'); for (attribute in values) { $table.append( $('<tr>').append( $('<td>').text(attribute), $('<td>').text(values\[attribute\]) ) ); } return $table; } var $oldValuesTable = createSubTable(audit.old\_values) var $newValuesTable = createSubTable(audit.new\_values) var $oldValuesCell = $('<td>').append($oldValuesTable); var $newValuesCell = $('<td>').append($newValuesTable); $newRow = $('<tr>').append( $modelCell, $eventCell, $userCell, $timeCell, $oldValuesCell, $newValuesCell ); $('#audits').prepend($newRow); }); </script> Replace and with your Pusher app key and cluster, and we’re done! your-app-key your-app-cluster Let’s test the app. Start your app as described earlier. Sign in as John Doe in one browser and Administrator in another so you can maintain concurrent sessions. Try making changes to some products as John Doe while viewing the dashboard as Administrator. The changes should show up on the dashboard in realtime. Conclusion In this article, we’ve added an audit dashboard to an existing application. We’ve gone ahead to add realtime functionality by displaying audits on the dashboard as they happen. Thanks to Laravel and Pusher, we were able to achieve these with minimal stress. You can check out the source code of the completed application on . GitHub Originally published on Pusher’s blog .
Share Your Thoughts