PHP code example of peters-development / laravel-model-logger

1. Go to this page and download the library: Download peters-development/laravel-model-logger 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/ */

    

peters-development / laravel-model-logger example snippets


use PetersDevelopment\ModelLogger\HasModelLogs;

class Order extends Model
{
    use HasModelLogs;
}

$order->log('Order was shipped');
$order->log('Payment received', ['amount' => 99.99, 'method' => 'ideal']);

$order->logs;        // MorphMany — collection of ModelLog
$log = $order->log('Status changed', ['from' => 'pending', 'to' => 'shipped']);

use PetersDevelopment\ModelLogger\ModelLog;

$log->user;                                // User model that performed the action
$logsByUser = ModelLog::forUser($userId)->get();

// config/model-logger.php (default — works without publishing)
return [
    'default' => env('MODEL_LOGGER_DEFAULT_CHANNEL', 'default'),

    'channels' => [
        'default' => [
            'table' => 'model_logs',
            'connection' => null,           // null = Laravel default
            'morph_key_type' => 'numeric',  // 'numeric' | 'uuid' | 'ulid'
            'user_model' => null,           // null = config('auth.providers.users.model')
        ],
    ],
];

// config/model-logger.php
return [
    'default' => 'default',

    'channels' => [
        'default' => [
            'table' => 'model_logs',
            'connection' => null,
            'morph_key_type' => 'numeric',
            'user_model' => null,
        ],
        'auth' => [
            'table' => 'auth_logs',
            'connection' => 'landlord',
            'morph_key_type' => 'numeric',
            'user_model' => \App\Models\User::class,
        ],
    ],
];

class User extends Authenticatable
{
    use HasModelLogs;

    public function getModelLogChannel(): string
    {
        return 'auth';
    }
}

use PetersDevelopment\ModelLogger\Schema\ModelLogsBlueprint;

return new class extends Migration {
    public function up(): void
    {
        Schema::connection('landlord')->create('auth_logs', function (Blueprint $table) {
            ModelLogsBlueprint::columns($table, morphKeyType: 'numeric');
        });
    }

    public function down(): void
    {
        Schema::connection('landlord')->dropIfExists('auth_logs');
    }
};

public function register(): void
{
    config()->set('model-logger.channels.mypackage', [
        'table' => 'mypackage_logs',
        'connection' => config('mypackage.database.connection'),
        'morph_key_type' => 'numeric',
    ]);
}
bash
php artisan vendor:publish --tag=model-logger-config