Add a realtime audit trail to your Laravel project

Introduction

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), who made the change, and when 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.

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:

realtime-audit-trail-demo

Prerequisites

Setup

We’ll start out with a small stock 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 cd into the project folder and install dependencies:

    composer install

Next, copy the .env.example to a new file called .env. Run the following command to generate an application encryption key:

    php artisan key:generate

Lastly, create a file called database.sqlite in the database directory and run the following command to set up and populate the database:

    php artisan migrate --seed

Creating the audit dashboard

We’ll use the laravel-auditing package to handle auditing. Let’s install the package:

    composer require owen-it/laravel-auditing

Next, we’ll publish the database migrations for the audit tables and run them:

1php artisan auditing:install
2    php 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 Product model (app/Models/Product.php):

  • use the OwenIt\Auditing\Auditable trait
  • implement the OwenIt\Auditing\Contracts\Auditable interface:
1<?php
2    
3    namespace App\Models;
4    
5    use Illuminate\Database\Eloquent\Model;
6    use OwenIt\Auditing\Contracts\Auditable;
7    
8    class Product extends Model implements Auditable
9    {
10      use \OwenIt\Auditing\Auditable;
11    
12      // ...
13    }

Now, whenever a change is made to a product, the details of the change will be recorded in the audits table.

We need to make a small change to our auditing configuration so the Audit model can properly map to our User model. This will enable us to write code like $audit→user→name to retrieve the name of the user who made the change. In the file config/audit.php, replace the value of model in the user array with the class name of our User model (App\Models\User::class)

1'user' => [
2      'primary_key' => 'id',
3      'foreign_key' => 'user_id',
4        
5      // replace the line below
6      'model'       => App\User::class,
7        
8      // with this
9      'model'       => App\Models\User::class,
10    ],

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 AllowOnlyAdmin.php in app/Http/Middleware with the following content:

1<?php
2    
3    namespace App\Http\Middleware;
4    
5    use Closure;
6    use Illuminate\Support\Facades\Auth;
7    
8    class AllowOnlyAdmin
9    {
10        public function handle($request, Closure $next)
11        {
12            if (Auth::user()->is_admin) {
13                return $next($request);
14            }
15            
16            abort(403);
17        }
18    }

Next, add the route for the audits at the end of your routes/web.php:

1Route::get('audits', 'AuditController@index')
2    ->middleware('auth', \App\Http\Middleware\AllowOnlyAdmin::class);

Let’s create the controller. We’ll generate the file app/Http/Controllers/AuditController.php by running:

    php artisan make:controller AuditController

Create an index method within the AuditController class with the following content:

1public function index()
2    {
3        $audits = \OwenIt\Auditing\Models\Audit::with('user')
4            ->orderBy('created_at', 'desc')->get();
5        return view('audits', ['audits' => $audits]);
6    }

Let’s build the view for our audits. Create the file resources/views/audits.blade.php with the following content:

1@extends('layouts.app')
2    
3    @section('content')
4      <div class="container">
5        <table class="table" >
6          <thead class="thead-dark">
7            <tr>
8              <th scope="col">Model</th>
9              <th scope="col">Action</th>
10              <th scope="col">User</th>
11              <th scope="col">Time</th>
12              <th scope="col">Old Values</th>
13              <th scope="col">New Values</th>
14            </tr>
15          </thead>
16          <tbody id="audits">
17            @foreach($audits as $audit)
18              <tr>
19                <td>{{ $audit->auditable_type }} (id: {{ $audit->auditable_id }})</td>
20                <td>{{ $audit->event }}</td>
21                <td>{{ $audit->user->name }}</td>
22                <td>{{ $audit->created_at }}</td>
23                <td>
24                  <table class="table">
25                    @foreach($audit->old_values as $attribute => $value)
26                      <tr>
27                        <td><b>{{ $attribute }}</b></td>
28                        <td>{{ $value }}</td>
29                      </tr>
30                    @endforeach
31                  </table>
32                </td>
33                <td>
34                  <table class="table">
35                    @foreach($audit->new_values as $attribute => $value)
36                      <tr>
37                        <td><b>{{ $attribute }}</b></td>
38                        <td>{{ $value }}</td>
39                      </tr>
40                    @endforeach
41                  </table>
42                </td>
43              </tr>
44            @endforeach
45          </tbody>
46        </table>
47    
48      </div>
49    @endsection

You can start your app by running:

php artisan serve

Then visit your app on http://localhost:8000. The stockt app comes with two default users: an admin user (Administrator, admin@stockt.test), and a regular user (John Doe, john@stockt.test). (Both passwords: secret) 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 http://localhost:8000/audits as Administrator to see the list of all changes made by all users.

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 Channels on the backend. Install the Pusher Laravel package:

1composer require pusher/pusher-http-laravel
2    php artisan vendor:publish --provider="Pusher\Laravel\PusherServiceProvider"

Edit your config/pusher.php so it looks like this:

1'connections' => [
2      'main' => [
3        'auth_key' => env('PUSHER_APP_KEY'),
4        'secret' => env('PUSHER_APP_SECRET'),
5        'app_id' => env('PUSHER_APP_ID'),
6        'options' => [
7          'cluster' => env('PUSHER_APP_CLUSTER'),
8        ],
9        'host' => null,
10        'port' => null,
11        'timeout' => null,
12      ],
13    ],

Go to the Pusher dashboard and create a new app. Copy your app credentials from the App Keys section and add them to your .env file:

1PUSHER_APP_ID=your-app-id
2    PUSHER_APP_KEY=your-app-key
3    PUSHER_APP_SECRET=your-app-secret
4    PUSHER_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:cache

The laravel-auditing package fires an event called Audited whenever a new audit is created. We’ll listen for this event and trigger a new-audit event on Pusher. Our frontend will listen for this event and add the new audit item to the table.

Create the event listener, app/Listeners/AuditedListener.php with the following content:

1<?php
2    
3    namespace App\Listeners;
4    
5    use OwenIt\Auditing\Events\Audited;
6    use Pusher\Laravel\Facades\Pusher;
7    
8    class AuditedListener
9    {
10      public function handle(Audited $event)
11      {
12        $audit = $event->audit->toArray();
13        $audit['user_name'] = $event->audit->user->name;
14        Pusher::trigger('audits', 'new-audit', ['audit' => $audit]);
15      }
16    }

Next, we’ll register the event listener in the app/Providers/EventServiceProvider.php:

1class EventServiceProvider extends ServiceProvider
2    {
3      protected $listen = [
4          \OwenIt\Auditing\Events\Audited::class => [
5              \App\Listeners\AuditedListener::class
6              ]
7      ];
8    
9      // ...
10    }

Here’s the code we’ll use to handle the event. We pull in the pusher-js library, subscribe to the audits channel and bind to the new-audit 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 resources/views/audits.blade.php:

1<script src="https://js.pusher.com/4.2/pusher.min.js"></script>
2    <script>
3      var socket = new Pusher("your-app-key", {
4          cluster: 'your-app-cluster',
5      });
6      socket.subscribe('audits')
7          .bind('new-audit', function (data) {
8              var audit = data.audit;
9              var $modelCell = $('<td>').text(audit.auditable_type + '(id: ' + audit.auditable_id + ')');
10              var $eventCell = $('<td>').text(audit.event);
11              var $userCell = $('<td>').text(audit.user_name);
12              var $timeCell = $('<td>').text(audit.created_at);
13    
14              function createSubTable(values) {
15                var $table = $('<table>').addClass('table');
16                  for (attribute in values) {
17                    $table.append(
18                      $('<tr>').append(
19                        $('<td>').text(attribute),
20                        $('<td>').text(values[attribute])
21                      )
22                    );
23                  }
24                  return $table;
25              }
26    
27              var $oldValuesTable = createSubTable(audit.old_values)
28              var $newValuesTable = createSubTable(audit.new_values)
29    
30              var $oldValuesCell = $('<td>').append($oldValuesTable);
31              var $newValuesCell = $('<td>').append($newValuesTable);
32    
33              $newRow = $('<tr>').append(
34                $modelCell,
35                $eventCell,
36                $userCell,
37                $timeCell,
38                $oldValuesCell,
39                $newValuesCell
40              );
41              $('#audits').prepend($newRow);
42          });
43    </script>

Replace your-app-key and your-app-cluster with your Pusher app key and cluster, and we’re done!

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 Channels, we were able to achieve these with minimal stress. You can check out the source code of the completed application on GitHub.