PHP code example of arpanihan / auditify

1. Go to this page and download the library: Download arpanihan/auditify library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

arpanihan / auditify example snippets


'xss_protection' => [
    'enabled' => true,
    'block' => true,
    'exclude_routes' => [
        'admin/articles/*',
        'posts/*/edit',
    ],
],

use Auditify\Facades\Auditify;

public function boot()
{
    // Restrict all Auditify dashboard and API routes to Admin users
    Auditify::auth(function ($request) {
        // Option A: Check user role (e.g. if using Spatie Role package)
        return $request->user() && $request->user()->hasRole('admin');

        // Option B: Check simple is_admin database flag
        // return $request->user() && $request->user()->is_admin;

        // Option C: Check a specific company email domain
        // return $request->user() && str_ends_with($request->user()->email, '@yourcompany.com');
    });
}

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Auditify\Traits\Auditable;

class Product extends Model
{
    use Auditable;
}

return [
    // Base URL route prefix: https://your-domain.com/auditify
    'route_prefix' => 'auditify',

    // Dashboard visual layout theme: 'dark' or 'light'
    'theme' => 'dark',

    // Middlewares applied to the dashboard routes
    'middleware' => [
        'web',
    ],

    // Log entries shown per page
    'pagination' => 20,

    // Track details
    'track_ip' => true,
    'track_user_agent' => true,
    'track_url' => true,

    // Authorization configuration
    'authorization' => [
        'enabled' => false,
        'gate' => 'view-auditify',
    ],

    // Automatic tracking configurations
    'track_auth_events' => true, // Login, Logout, Failed logins

    /*
     * Mappings of user attributes for email, username, and phone numbers.
     * These will be dynamically extracted from your User model/login credentials.
     */
    'user_fields' => [
        'email' => 'email',
        'username' => 'username',
        'phone' => 'phone',
    ],

    'track_page_visits' => true, // Page visits

    // Threat alerting configurations & thresholds
    'alerts' => [
        'enabled' => false,
        'recipients' => ['[email protected]'],
        'channels' => ['mail', 'log'],
        'sensitive_modules' => ['User', 'Role', 'Permission', 'Setting', 'Config'],
        'thresholds' => [
            'failed_logins' => 3,
            'failed_logins_timeframe' => 5, // minutes
            'mass_delete' => 5,
            'mass_delete_timeframe' => 5, // minutes
            'bulk_update' => 10,
            'bulk_update_timeframe' => 5, // minutes
        ],
    ],

    // Firewall scanning
    'xss_protection' => [
        'enabled' => true,
        'block' => true,         // Abort requests with HTTP 403 when script is found
        'exclude_routes' => [
            // 'admin/rich-text/*',
        ],
    ],

    // Global model auditing
    'auto_audit_models' => true, // Tracks all model lifecycle changes globally

    /*
     * Interval (in seconds) for frontend auto-polling of new unread security alerts.
     * Set to 60 or higher for better performance, or set to 0 to disable polling entirely.
     */
    'security_polling_interval' => 0,

    'exclude_models' => [        // Model classes to exclude from global auditing
        // App\Models\Session::class,
    ],

    // Pruning configuration
    'pruning' => [
        'keep_days' => 90,       // Default age in days for keeping historical log rows
    ],
];

use Auditify\Facades\Auditify;

Auditify::logAction(
    action: 'PUBLISH',
    module: 'Article',
    description: 'User published a new article',
    oldValues: ['status' => 'draft'],
    newValues: ['status' => 'published'],
    userId: auth()->id(), // optional, defaults to current authenticated user
    subject: $article     // optional, polymorphic eloquent model instance
);

Auditify::logActivity(
    activity: 'Exported Reports (PDF)',
    url: request()->fullUrl(), // optional, defaults to request URL
    userId: auth()->id(),      // optional
    properties: ['timeframe' => '30_days'] // optional metadata payload
);

Auditify::logSecurity(
    title: 'Suspicious Endpoint Access',
    description: 'Blocked access attempt to restricted legacy endpoint',
    severity: 'high', // options: low, medium, high, critical
    payload: request()->all() // optional JSON request context
);

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Order;
use Auditify\Facades\Auditify; // Import the Auditify facade

class OrderController extends Controller
{
    /**
     * Cancel a customer order and log the audit trail.
     */
    public function cancel(Request $request, $id)
    {
        // 1. Retrieve the order record from the database
        $order = Order::findOrFail($id);

        // Capture the original status for audit comparison
        $oldStatus = $order->status;

        // 2. Perform the cancellation business logic
        $order->update([
            'status' => 'cancelled',
            'cancelled_at' => now(),
            'cancellation_reason' => $request->input('reason')
        ]);

        // 3. Manually Log a database Action showing the status transition
        Auditify::logAction(
            action: 'CANCEL_ORDER',
            module: 'Order',
            description: "Order #{$order->id} cancelled by user due to: " . $request->input('reason'),
            oldValues: ['status' => $oldStatus],
            newValues: ['status' => 'cancelled'],
            userId: auth()->id(), // Associate log with the logged-in administrator
            subject: $order      // Link the polymorphic subject relation to this order model
        );

        // 4. Log a general user activity for dashboard stats tracking
        Auditify::logActivity(
            activity: 'Cancelled Order',
            properties: [
                'order_id' => $order->id,
                'total_amount' => $order->total_price
            ]
        );

        // 5. Send a redirect response back to the admin portal
        return redirect()->back()->with('success', 'Order cancelled and action audited.');
    }
}

use Auditify\Facades\Auditify;

// Pauses auditing automatically for the duration of the callback function
Auditify::withoutAuditing(function () {
    // Generate 1,000 dummy articles silently without log spam
    Article::factory()->count(1000)->create();
});

use Auditify\Facades\Auditify;

// 1. Manually disable auditing
Auditify::disableAuditing();

// 2. Perform sequential operations...
User::insert($massiveCsvData);

// 3. Manually re-enable auditing
Auditify::enableAuditing();

use Illuminate\Support\Facades\Schedule;

Schedule::command('auditify:prune --days=90')->daily();
bash
php artisan auditify:install
bash
php artisan optimize:clear
bash
php artisan serve