├── phpstan-baseline.neon ├── .github ├── FUNDING.yml ├── dependabot.yml ├── ISSUE_TEMPLATE │ ├── config.yml │ └── bug.yml └── workflows │ ├── dependabot-auto-merge.yml │ ├── run-tests.yml │ └── code-quality.yml ├── assets ├── logo.png └── RestoreChanges.gif ├── CHANGELOG.md ├── tests ├── Pest.php ├── ExampleTest.php ├── ArchTest.php ├── Models │ └── TestFakeModel.php ├── Jobs │ ├── ProcessClearExceededLimitTest.php │ ├── ProcessRestoreChangesTest.php │ ├── ProcessRemoveDuplicatesTest.php │ └── ProcessCreateEntryTest.php ├── Commands │ ├── InstallCommandTest.php │ └── RestoreChangeCommandTest.php ├── database │ └── migrations │ │ └── 2025_05_07_100000_create_fake_model_table.php ├── Traits │ └── ElogquentTest.php ├── TestCase.php ├── Observers │ └── ElogquentObserverTest.php └── Repositories │ └── ElogquentDatabaseRepositoryTest.php ├── pint.json ├── src ├── Exceptions │ ├── ElogquentError.php │ ├── ElogquentInstallingError.php │ └── ElogquentDatabaseError.php ├── Traits │ └── Elogquent.php ├── Contracts │ └── ElogquentRepositoryInterface.php ├── Jobs │ ├── ProcessRestoreChanges.php │ ├── ProcessRemoveDuplicates.php │ ├── ProcessClearExceededLimit.php │ └── ProcessCreateEntry.php ├── Models │ └── ElogquentEntry.php ├── Commands │ ├── InstallCommand.php │ └── RestoreChangeCommand.php ├── ElogquentServiceProvider.php ├── Observers │ └── ElogquentObserver.php └── Repositories │ └── ElogquentDatabaseRepository.php ├── .gitignore ├── phpstan.neon.dist ├── CONTRIBUTING.md ├── database ├── factories │ └── ElogquentEntryFactory.php └── migrations │ └── 2025_05_07_100000_create_model_changes_table.php ├── LICENSE.md ├── phpunit.xml.dist ├── composer.json ├── config └── elogquent.php ├── README.md └── LICENSE /phpstan-baseline.neon: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: luissantiago 2 | -------------------------------------------------------------------------------- /assets/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LuisSantiago/elogquent/HEAD/assets/logo.png -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to `elogquent` will be documented in this file. 4 | -------------------------------------------------------------------------------- /assets/RestoreChanges.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LuisSantiago/elogquent/HEAD/assets/RestoreChanges.gif -------------------------------------------------------------------------------- /tests/Pest.php: -------------------------------------------------------------------------------- 1 | in(__DIR__); 6 | -------------------------------------------------------------------------------- /tests/ExampleTest.php: -------------------------------------------------------------------------------- 1 | toBeTrue(); 5 | }); 6 | -------------------------------------------------------------------------------- /tests/ArchTest.php: -------------------------------------------------------------------------------- 1 | expect(['dd', 'dump', 'ray']) 5 | ->each->not->toBeUsed(); 6 | -------------------------------------------------------------------------------- /pint.json: -------------------------------------------------------------------------------- 1 | { 2 | "preset": "laravel", 3 | "rules": { 4 | "simplified_null_return": true, 5 | "array_indentation": false, 6 | "new_with_parentheses": { 7 | "anonymous_class": true, 8 | "named_class": true 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/Exceptions/ElogquentError.php: -------------------------------------------------------------------------------- 1 | create(); 10 | 11 | ProcessClearExceededLimit::dispatchSync( 12 | modelClass: $model->getModelClassName(), 13 | modelKey: $model->getModelId(), 14 | limit: 1 15 | ); 16 | 17 | $this->assertDatabaseCount('elogquent_entries', 1); 18 | }); 19 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: false 2 | contact_links: 3 | - name: Ask a question 4 | url: https://github.com/luissantiago/elogquent/discussions/new?category=q-a 5 | about: Ask the community for help 6 | - name: Request a feature 7 | url: https://github.com/luissantiago/elogquent/discussions/new?category=ideas 8 | about: Share ideas for new features 9 | - name: Report a security issue 10 | url: https://github.com/luissantiago/elogquent/security/policy 11 | about: Learn how to notify us for sensitive bugs 12 | -------------------------------------------------------------------------------- /phpstan.neon.dist: -------------------------------------------------------------------------------- 1 | includes: 2 | - phpstan-baseline.neon 3 | 4 | parameters: 5 | level: 5 6 | paths: 7 | - src 8 | - config 9 | - database 10 | excludePaths: 11 | - tests/*/data/* 12 | tmpDir: build/phpstan 13 | checkOctaneCompatibility: true 14 | checkModelProperties: true 15 | ignoreErrors: 16 | - identifier: function.alreadyNarrowedType 17 | - identifier: trait.unused 18 | - identifier: larastan.noEnvCallsOutsideOfConfig 19 | - identifier: larastan.noUnnecessaryCollectionCall 20 | -------------------------------------------------------------------------------- /tests/Commands/InstallCommandTest.php: -------------------------------------------------------------------------------- 1 | artisan('elogquent:install') 5 | ->expectsOutput('Publishing Elogquent Configuration...') 6 | ->expectsOutput('Publishing Elogquent Migrations...') 7 | ->expectsOutput('Publishing Elogquent ServiceProvider...') 8 | ->expectsOutput('Elogquent installed successfully.') 9 | ->expectsQuestion('Do you want to run the database migrations now?', 0) 10 | ->assertExitCode(0); 11 | }); 12 | -------------------------------------------------------------------------------- /src/Traits/Elogquent.php: -------------------------------------------------------------------------------- 1 | morphMany(ElogquentEntry::class, 'model'); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /tests/Jobs/ProcessRestoreChangesTest.php: -------------------------------------------------------------------------------- 1 | create(); 11 | 12 | ProcessRestoreChanges::dispatchSync( 13 | model: $model, 14 | changes: ['column' => 'foo', 'value' => 'bar'], 15 | ); 16 | 17 | $this->assertDatabaseHas('elogquent_entries', [ 18 | 'column' => 'foo', 19 | 'value' => 'bar', 20 | ]); 21 | }); 22 | -------------------------------------------------------------------------------- /tests/Jobs/ProcessRemoveDuplicatesTest.php: -------------------------------------------------------------------------------- 1 | create(); 12 | 13 | ProcessRemoveDuplicates::dispatchSync( 14 | modelClass: $model->getModelClassName(), 15 | modelKey: $model->getModelId(), 16 | changes: [$model->getColumn() => $model->getValue()] 17 | ); 18 | 19 | $this->assertDatabaseEmpty('elogquent_entries'); 20 | }); 21 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines 2 | 3 | Thank you for considering contributing to this project! To maintain a clean and consistent codebase, please follow the guidelines below. 4 | 5 | ## 📦 Requirements 6 | 7 | Before you begin, make sure you have: 8 | 9 | - PHP >= 8.2 10 | - Laravel >= 11 11 | - Composer 12 | - Installed dependencies via `composer install` 13 | 14 | ## 🧑‍💻 Code Style & Standards 15 | 16 | This project adheres to the [PSR-12](https://www.php-fig.org/psr/psr-12/) coding standard and uses **[Laravel Pint](https://laravel.com/docs/pint)** for code formatting. 17 | 18 | ### Code Formatting 19 | 20 | Run Pint to automatically format your code before committing: 21 | 22 | ```bash 23 | vendor/bin/pint 24 | -------------------------------------------------------------------------------- /tests/Jobs/ProcessCreateEntryTest.php: -------------------------------------------------------------------------------- 1 | create(); 10 | 11 | ProcessCreateEntry::dispatchSync( 12 | modelClass: $model->getModelClassName(), 13 | modelKey: $model->getModelId(), 14 | changes: [$model->getColumn() => $model->getValue()] 15 | ); 16 | 17 | $this->assertDatabaseHas('elogquent_entries', [ 18 | 'model_type' => $model->getModelClassName(), 19 | 'model_id' => $model->getModelId(), 20 | 'column' => $model->getColumn(), 21 | 'value' => $model->getValue(), 22 | ]); 23 | }); 24 | -------------------------------------------------------------------------------- /src/Contracts/ElogquentRepositoryInterface.php: -------------------------------------------------------------------------------- 1 | restoreChanges( 28 | model: $this->model, 29 | changes: $this->changes, 30 | ); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /database/factories/ElogquentEntryFactory.php: -------------------------------------------------------------------------------- 1 | $faker->numerify('##'), 23 | 'model_type' => Str::camel(implode(' ', $faker->words())), 24 | 'column' => $faker->word(), 25 | 'value' => $faker->word(), 26 | 'created_at' => $faker->dateTime(), 27 | ]; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /tests/database/migrations/2025_05_07_100000_create_fake_model_table.php: -------------------------------------------------------------------------------- 1 | getConnection()); 17 | 18 | $schema->create('fake_models', function (Blueprint $table) { 19 | $table->id(); 20 | $table->tinyText('name'); 21 | }); 22 | } 23 | 24 | public function down(): void 25 | { 26 | $schema = Schema::connection($this->getConnection()); 27 | 28 | $schema->dropIfExists('fake_models'); 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /src/Jobs/ProcessRemoveDuplicates.php: -------------------------------------------------------------------------------- 1 | removeChanges( 28 | modelClass: $this->modelClass, 29 | modelKey: $this->modelKey, 30 | changes: $this->changes, 31 | ); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/Jobs/ProcessClearExceededLimit.php: -------------------------------------------------------------------------------- 1 | removeExceededLimit( 28 | modelClass: $this->modelClass, 29 | modelKey: $this->modelKey, 30 | limit: $this->limit, 31 | ); 32 | 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /tests/Traits/ElogquentTest.php: -------------------------------------------------------------------------------- 1 | toUseTraits(Elogquent::class); 15 | }); 16 | 17 | it('registers event listeners when package is enabled', function () { 18 | $model = new TestFakeModel(); 19 | $model::bootTraits(); 20 | $model::boot(); 21 | 22 | expect(Event::hasListeners('eloquent.updating: '.TestFakeModel::class))->toBeTrue(); 23 | }); 24 | 25 | it('model with the trait has the allChanges the relationship', function () { 26 | $model = new TestFakeModel(); 27 | $model::bootTraits(); 28 | $model::boot(); 29 | 30 | expect(TestFakeModel::class)->toHaveMethod('allChanges'); 31 | }); 32 | -------------------------------------------------------------------------------- /src/Jobs/ProcessCreateEntry.php: -------------------------------------------------------------------------------- 1 | user()?->getAuthIdentifier() : null; 28 | 29 | $repository->create( 30 | modelClass: $this->modelClass, 31 | modelKey: $this->modelKey, 32 | changes: $this->changes, 33 | userId: $userId 34 | ); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /database/migrations/2025_05_07_100000_create_model_changes_table.php: -------------------------------------------------------------------------------- 1 | getConnection()); 17 | 18 | $schema->create('elogquent_entries', function (Blueprint $table) { 19 | $table->id(); 20 | $table->foreignId('user_id')->nullable(); 21 | $table->morphs('model'); 22 | $table->tinyText('column'); 23 | $table->string('value'); 24 | $table->timestamp('created_at')->useCurrent(); 25 | }); 26 | } 27 | 28 | public function down(): void 29 | { 30 | $schema = Schema::connection($this->getConnection()); 31 | 32 | $schema->dropIfExists('elogquent_entries'); 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) luissantiago 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /.github/workflows/dependabot-auto-merge.yml: -------------------------------------------------------------------------------- 1 | name: dependabot-auto-merge 2 | on: pull_request_target 3 | 4 | permissions: 5 | pull-requests: write 6 | contents: write 7 | 8 | jobs: 9 | dependabot: 10 | runs-on: ubuntu-latest 11 | timeout-minutes: 5 12 | if: ${{ github.actor == 'dependabot[bot]' }} 13 | steps: 14 | 15 | - name: Dependabot metadata 16 | id: metadata 17 | uses: dependabot/fetch-metadata@v2.4.0 18 | with: 19 | github-token: "${{ secrets.GITHUB_TOKEN }}" 20 | 21 | - name: Auto-merge Dependabot PRs for semver-minor updates 22 | if: ${{steps.metadata.outputs.update-type == 'version-update:semver-minor'}} 23 | run: gh pr merge --auto --merge "$PR_URL" 24 | env: 25 | PR_URL: ${{github.event.pull_request.html_url}} 26 | GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} 27 | 28 | - name: Auto-merge Dependabot PRs for semver-patch updates 29 | if: ${{steps.metadata.outputs.update-type == 'version-update:semver-patch'}} 30 | run: gh pr merge --auto --merge "$PR_URL" 31 | env: 32 | PR_URL: ${{github.event.pull_request.html_url}} 33 | GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} 34 | -------------------------------------------------------------------------------- /phpunit.xml.dist: -------------------------------------------------------------------------------- 1 | 2 | 18 | 19 | 20 | tests 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | ./src 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /src/Models/ElogquentEntry.php: -------------------------------------------------------------------------------- 1 | morphTo('model', 'model_type', 'model_id'); 26 | } 27 | 28 | public function restore(): void 29 | { 30 | $this->getRelation('modelChanged') 31 | ->update([$this->getColumn() => $this->getValue()]); 32 | } 33 | 34 | #[Override] 35 | public function getConnectionName(): ?string 36 | { 37 | return config('elogquent.database_connection'); 38 | } 39 | 40 | public function getModelClassName(): string 41 | { 42 | return $this->getAttribute('model_type'); 43 | } 44 | 45 | public function getModelId(): int 46 | { 47 | return $this->getAttribute('model_id'); 48 | } 49 | 50 | public function getColumn(): string 51 | { 52 | return $this->getAttribute('column'); 53 | } 54 | 55 | public function getValue(): string 56 | { 57 | return $this->getAttribute('value'); 58 | } 59 | 60 | public static function newFactory(): ElogquentEntryFactory 61 | { 62 | return ElogquentEntryFactory::new(); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /tests/TestCase.php: -------------------------------------------------------------------------------- 1 | loadMigrationsFrom( 18 | __DIR__.'/../database/migrations', 19 | ); 20 | $this->loadMigrationsFrom( 21 | __DIR__.'/database/migrations', 22 | ); 23 | 24 | } 25 | 26 | protected function getEnvironmentSetUp($app): void 27 | { 28 | $app['config']->set('database.default', 'sqlite'); 29 | $app['config']->set('database.connections.sqlite', [ 30 | 'driver' => 'sqlite', 31 | 'database' => ':memory:', 32 | 'prefix' => '', 33 | ]); 34 | $app['config']->set('elogquent.database_connection', 'sqlite'); 35 | $app['config']->set('elogquent.queue', 'sync'); 36 | } 37 | 38 | protected function getPackageProviders($app): array 39 | { 40 | return [ 41 | ElogquentServiceProvider::class, 42 | ]; 43 | } 44 | 45 | public function mockModel(array $changes = ['name' => 'Luis'], int $key = 1): object 46 | { 47 | $model = Mockery::mock(Model::class); 48 | $model->expects('getKey') 49 | ->andReturn($key); 50 | 51 | $model->expects('getDirty') 52 | ->andReturn($changes); 53 | 54 | return $model; 55 | } 56 | 57 | public function createEntryModel(array $attributes = []): ElogquentEntry 58 | { 59 | return ElogquentEntry::factory() 60 | ->create($attributes); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /.github/workflows/run-tests.yml: -------------------------------------------------------------------------------- 1 | name: Tests 2 | 3 | on: 4 | push: 5 | paths: 6 | - '**.php' 7 | - '.github/workflows/run-tests.yml' 8 | - 'phpunit.xml.dist' 9 | - 'composer.json' 10 | - 'composer.lock' 11 | 12 | concurrency: 13 | group: ${{ github.workflow }}-${{ github.ref }} 14 | cancel-in-progress: true 15 | 16 | jobs: 17 | test: 18 | runs-on: ${{ matrix.os }} 19 | timeout-minutes: 5 20 | strategy: 21 | fail-fast: true 22 | matrix: 23 | os: [ubuntu-latest] 24 | php: [8.4, 8.3] 25 | laravel: [12.*, 11.*] 26 | stability: [prefer-stable] 27 | include: 28 | - laravel: 12.* 29 | testbench: 10.* 30 | - laravel: 11.* 31 | testbench: 9.* 32 | 33 | name: P${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.stability }} - ${{ matrix.os }} 34 | 35 | steps: 36 | - name: Checkout code 37 | uses: actions/checkout@v6 38 | 39 | - name: Setup PHP 40 | uses: shivammathur/setup-php@v2 41 | with: 42 | php-version: ${{ matrix.php }} 43 | extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv, imagick, fileinfo 44 | coverage: none 45 | 46 | - name: Setup problem matchers 47 | run: | 48 | echo "::add-matcher::${{ runner.tool_cache }}/php.json" 49 | echo "::add-matcher::${{ runner.tool_cache }}/phpunit.json" 50 | 51 | - name: Install dependencies 52 | run: | 53 | composer require "laravel/framework:${{ matrix.laravel }}" "orchestra/testbench:${{ matrix.testbench }}" --no-interaction --no-update 54 | composer update --${{ matrix.stability }} --prefer-dist --no-interaction 55 | 56 | - name: List Installed Dependencies 57 | run: composer show -D 58 | 59 | - name: Execute tests 60 | run: vendor/bin/pest --ci 61 | -------------------------------------------------------------------------------- /src/Commands/InstallCommand.php: -------------------------------------------------------------------------------- 1 | comment('Publishing Elogquent Configuration...'); 25 | $this->callSilent('vendor:publish', ['--tag' => 'elogquent-config']); 26 | 27 | $this->comment('Publishing Elogquent Migrations...'); 28 | $this->callSilent('vendor:publish', ['--tag' => 'elogquent-migrations']); 29 | 30 | $this->registerElogquentServiceProvider(); 31 | } catch (Exception $e) { 32 | throw new ElogquentInstallingError($e->getMessage()); 33 | } 34 | 35 | $this->info('Elogquent installed successfully.'); 36 | $migrate = select( 37 | label: 'Do you want to run the database migrations now?', 38 | options: [1 => 'yes', 0 => 'no'], 39 | ); 40 | 41 | if ($migrate === 0) { 42 | return self::SUCCESS; 43 | } 44 | 45 | $this->info('Running database migrations...'); 46 | $this->call('migrate'); 47 | 48 | return self::SUCCESS; 49 | } 50 | 51 | protected function registerElogquentServiceProvider(): void 52 | { 53 | $this->comment('Publishing Elogquent ServiceProvider...'); 54 | 55 | // @phpstan-ignore-next-line 56 | if (method_exists(ServiceProvider::class, 'addProviderToBootstrapFile') && 57 | ServiceProvider::addProviderToBootstrapFile(ElogquentServiceProvider::class)) { 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /.github/workflows/code-quality.yml: -------------------------------------------------------------------------------- 1 | name: Code Quality 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | paths: 8 | - '**.php' 9 | - 'composer.json' 10 | - 'pint.json' 11 | - 'phpstan.neon.dist' 12 | pull_request: 13 | paths: 14 | - '**.php' 15 | - 'composer.json' 16 | - 'pint.json' 17 | - 'phpstan.neon.dist' 18 | 19 | jobs: 20 | setup: 21 | name: Install dependencies 22 | runs-on: ubuntu-latest 23 | outputs: 24 | cache-hit: ${{ steps.composer-cache.outputs.cache-hit }} 25 | steps: 26 | - uses: actions/checkout@v6 27 | 28 | - name: Set up PHP 29 | uses: shivammathur/setup-php@v2 30 | with: 31 | php-version: '8.3' 32 | 33 | - name: Cache Composer dependencies 34 | id: composer-cache 35 | uses: actions/cache@v3 36 | with: 37 | path: vendor 38 | key: composer-${{ hashFiles('composer.lock') }} 39 | restore-keys: composer- 40 | 41 | - name: Install dependencies 42 | run: composer install --prefer-dist --no-progress 43 | 44 | pint: 45 | name: Run Laravel Pint 46 | needs: setup 47 | runs-on: ubuntu-latest 48 | steps: 49 | - uses: actions/checkout@v6 50 | 51 | - name: Set up PHP 52 | uses: shivammathur/setup-php@v2 53 | with: 54 | php-version: '8.3' 55 | 56 | - name: Install dependencies 57 | run: composer install --prefer-dist --no-progress 58 | 59 | - name: Run Pint (check mode) 60 | run: vendor/bin/pint --test 61 | 62 | phpstan: 63 | name: Run PHPStan 64 | needs: setup 65 | runs-on: ubuntu-latest 66 | steps: 67 | - uses: actions/checkout@v6 68 | 69 | - name: Set up PHP 70 | uses: shivammathur/setup-php@v2 71 | with: 72 | php-version: '8.3' 73 | 74 | - name: Install dependencies 75 | run: composer install --prefer-dist --no-progress 76 | 77 | - name: Run PHPStan 78 | run: vendor/bin/phpstan analyse 79 | -------------------------------------------------------------------------------- /src/ElogquentServiceProvider.php: -------------------------------------------------------------------------------- 1 | registerCommands(); 19 | $this->registerPublishing(); 20 | } 21 | 22 | /** 23 | * Register the service provider. 24 | */ 25 | #[\Override] 26 | public function register(): void 27 | { 28 | $this->app->bind(ElogquentRepositoryInterface::class, ElogquentDatabaseRepository::class); 29 | if (! app()->configurationIsCached()) { 30 | $this->mergeConfigFrom( 31 | __DIR__.'/../config/elogquent.php', 'elogquent' 32 | ); 33 | } 34 | } 35 | 36 | /** 37 | * Register the package's commands. 38 | */ 39 | protected function registerCommands(): void 40 | { 41 | if ($this->app->runningInConsole()) { 42 | $this->commands([ 43 | InstallCommand::class, 44 | RestoreChangeCommand::class, 45 | ]); 46 | } 47 | } 48 | 49 | /** 50 | * Register the package's publishable resources. 51 | */ 52 | private function registerPublishing(): void 53 | { 54 | if ($this->app->runningInConsole()) { 55 | $publishesMigrationsMethod = method_exists($this, 'publishesMigrations') 56 | ? 'publishesMigrations' 57 | : 'publishes'; 58 | 59 | $this->{$publishesMigrationsMethod}([ 60 | __DIR__.'/../database/migrations' => database_path('migrations'), 61 | ], 'elogquent-migrations'); 62 | 63 | $this->publishes([ 64 | __DIR__.'/../config/elogquent.php' => config_path('elogquent.php'), 65 | ], 'elogquent-config'); 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /tests/Observers/ElogquentObserverTest.php: -------------------------------------------------------------------------------- 1 | mockModel(); 17 | 18 | Config::set('elogquent.included_columns', ['name']); 19 | Config::set('elogquent.excluded_columns', []); 20 | 21 | $sut = new ElogquentObserver(); 22 | $sut->updating($model); 23 | 24 | Bus::assertChained([ 25 | ProcessRemoveDuplicates::class, 26 | ProcessCreateEntry::class, 27 | ]); 28 | }); 29 | 30 | it('ignore changes when the model has no changes in configured columns', function () { 31 | $model = $this->mockModel(); 32 | 33 | Config::set('elogquent.included_columns', []); 34 | Config::set('elogquent.excluded_columns', ['name']); 35 | 36 | $sut = new ElogquentObserver(); 37 | $sut->updating($model); 38 | }); 39 | 40 | it('process limit entries if its configured globally', function () { 41 | $model = $this->mockModel(); 42 | Config::set('elogquent.changes_limit', 1); 43 | 44 | $sut = new ElogquentObserver(); 45 | $sut->updating($model); 46 | 47 | Bus::assertChained([ 48 | ProcessRemoveDuplicates::class, 49 | ProcessCreateEntry::class, 50 | ProcessClearExceededLimit::class, 51 | ]); 52 | }); 53 | 54 | it('process limit entries if its configured for the model', function () { 55 | $model = $this->mockModel(); 56 | Config::set('elogquent.remove_previous_duplicates', true); 57 | Config::set('elogquent.model_changes_limit', [ 58 | get_class($model) => 1, 59 | ]); 60 | 61 | $sut = new ElogquentObserver(); 62 | $sut->updating($model); 63 | 64 | Bus::assertChained([ 65 | ProcessRemoveDuplicates::class, 66 | ProcessCreateEntry::class, 67 | ProcessClearExceededLimit::class, 68 | ]); 69 | }); 70 | -------------------------------------------------------------------------------- /tests/Commands/RestoreChangeCommandTest.php: -------------------------------------------------------------------------------- 1 | false]); 7 | 8 | $this->artisan('elogquent:restore-changes') 9 | ->expectsOutputToContain('enable elogquent in config/elogquent.php') 10 | ->assertExitCode(0); 11 | }); 12 | 13 | it('elogquent is enabled but has no entries', function () { 14 | $this->artisan('elogquent:restore-changes') 15 | ->expectsOutputToContain('No models with changes found.') 16 | ->assertExitCode(0); 17 | }); 18 | 19 | it('the user is trying to restore a non-existent id', function () { 20 | $modelClass = ElogquentEntry::class; 21 | ElogquentEntry::factory()->create([ 22 | 'model_id' => 1, 23 | 'model_type' => $modelClass, 24 | ]); 25 | 26 | $this->artisan('elogquent:restore-changes') 27 | ->expectsChoice('Select the Model you want to restore:', $modelClass, [$modelClass => $modelClass]) 28 | ->expectsQuestion('Which model id would you like to restore?', 2) 29 | ->expectsOutputToContain('with id 2 not found') 30 | ->assertExitCode(0); 31 | }); 32 | 33 | it('the command select a model and a id to restore', function () { 34 | $modelClass = ElogquentEntry::class; 35 | ElogquentEntry::factory()->create([ 36 | 'model_id' => 1, 37 | 'model_type' => $modelClass, 38 | 'column' => 'name', 39 | 'value' => 'Luis', 40 | 'created_at' => '2025-05-07 10:00:00', 41 | ]); 42 | 43 | $this->artisan('elogquent:restore-changes') 44 | ->expectsChoice('Select the Model you want to restore:', $modelClass, [$modelClass => $modelClass]) 45 | ->expectsQuestion('Which model id would you like to restore?', 1) 46 | ->expectsChoice('Which model attributes you like to restore?', ['name'], ['name']) 47 | ->expectsChoice('Which change for the column name would you like to restore?', 48 | 'Luis', ['Luis (2025-05-07 10:00:00)', 'Luis'] 49 | ) 50 | ->expectsConfirmation('Do you want to restore the changes?', true) 51 | ->assertExitCode(0); 52 | 53 | $this->assertDatabaseHas('elogquent_entries', [ 54 | 'model_id' => 1, 55 | 'model_type' => $modelClass, 56 | 'column' => 'name', 57 | 'value' => 'Luis', 58 | ]); 59 | }); 60 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug.yml: -------------------------------------------------------------------------------- 1 | name: Bug Report 2 | description: Report an Issue or Bug with the Package 3 | title: "[Bug]: " 4 | labels: ["bug"] 5 | body: 6 | - type: markdown 7 | attributes: 8 | value: | 9 | We're sorry to hear you have a problem. Can you help us solve it by providing the following details. 10 | - type: textarea 11 | id: what-happened 12 | attributes: 13 | label: What happened? 14 | description: What did you expect to happen? 15 | placeholder: I cannot currently do X thing because when I do, it breaks X thing. 16 | validations: 17 | required: true 18 | - type: textarea 19 | id: how-to-reproduce 20 | attributes: 21 | label: How to reproduce the bug 22 | description: How did this occur, please add any config values used and provide a set of reliable steps if possible. 23 | placeholder: When I do X I see Y. 24 | validations: 25 | required: true 26 | - type: input 27 | id: package-version 28 | attributes: 29 | label: Package Version 30 | description: What version of our Package are you running? Please be as specific as possible 31 | placeholder: 2.0.0 32 | validations: 33 | required: true 34 | - type: input 35 | id: php-version 36 | attributes: 37 | label: PHP Version 38 | description: What version of PHP are you running? Please be as specific as possible 39 | placeholder: 8.2.0 40 | validations: 41 | required: true 42 | - type: input 43 | id: laravel-version 44 | attributes: 45 | label: Laravel Version 46 | description: What version of Laravel are you running? Please be as specific as possible 47 | placeholder: 9.0.0 48 | validations: 49 | required: true 50 | - type: dropdown 51 | id: operating-systems 52 | attributes: 53 | label: Which operating systems does this happen with? 54 | description: You may select more than one. 55 | multiple: true 56 | options: 57 | - macOS 58 | - Windows 59 | - Linux 60 | - type: textarea 61 | id: notes 62 | attributes: 63 | label: Notes 64 | description: Use this field to provide any other notes that you feel might be relevant to the issue. 65 | validations: 66 | required: false 67 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "luissantiago/elogquent", 3 | "description": "Listens to Eloquent model events and logs configured attribute changes into a history table.", 4 | "keywords": [ 5 | "elogquent", 6 | "laravel", 7 | "eloquent", 8 | "audit", 9 | "auditing", 10 | "log", 11 | "history", 12 | "model events" 13 | ], 14 | "homepage": "https://github.com/luissantiago/elogquent", 15 | "license": "MIT", 16 | "authors": [ 17 | { 18 | "name": "Luis Santiago", 19 | "email": "soyluissantiagotorres@gmail.com", 20 | "role": "Developer" 21 | } 22 | ], 23 | "require": { 24 | "php": "^8.2 || ^8.3 || ^8.4", 25 | "illuminate/database": "^11.0 || ^12.0", 26 | "illuminate/support": "^11.0 || ^12.0", 27 | "laravel/prompts": "^0.2 || ^0.3" 28 | }, 29 | "require-dev": { 30 | "larastan/larastan": "^2.9 || ^3.0", 31 | "laravel/pint": "^1.22 || ^2.0", 32 | "orchestra/testbench": "^10.0 || ^11.0", 33 | "pestphp/pest": "^3.0", 34 | "pestphp/pest-plugin-arch": "^3.0", 35 | "pestphp/pest-plugin-laravel": "^3.0", 36 | "phpstan/extension-installer": "^1.0", 37 | "phpstan/phpstan-deprecation-rules": "^2.0", 38 | "phpstan/phpstan-phpunit": "^2.0" 39 | }, 40 | "autoload": { 41 | "psr-4": { 42 | "Elogquent\\": "src/" 43 | }, 44 | "classmap": [ 45 | "database/factories" 46 | ] 47 | }, 48 | "autoload-dev": { 49 | "psr-4": { 50 | "Elogquent\\Tests\\": "tests/", 51 | "Workbench\\App\\": "workbench/app/" 52 | } 53 | }, 54 | "scripts": { 55 | "post-autoload-dump": "@composer prepare", 56 | "prepare": "@php vendor/bin/testbench package:discover --ansi", 57 | "analyse": "vendor/bin/phpstan analyse", 58 | "test": "vendor/bin/pest", 59 | "test-coverage": "vendor/bin/pest --coverage", 60 | "format": "vendor/bin/pint" 61 | }, 62 | "config": { 63 | "sort-packages": true, 64 | "allow-plugins": { 65 | "pestphp/pest-plugin": true, 66 | "phpstan/extension-installer": true 67 | } 68 | }, 69 | "extra": { 70 | "laravel": { 71 | "providers": [ 72 | "Elogquent\\ElogquentServiceProvider" 73 | ] 74 | } 75 | }, 76 | "minimum-stability": "dev", 77 | "prefer-stable": true, 78 | "support": { 79 | "issues": "https://github.com/luissantiago/elogquent/issues", 80 | "source": "https://github.com/luissantiago/elogquent" 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/Observers/ElogquentObserver.php: -------------------------------------------------------------------------------- 1 | getKey(); 19 | $modelClass = get_class($model); 20 | $changes = $this->getChanges($model->getDirty()); 21 | 22 | if (is_null($modelKey) || $changes->isEmpty()) { 23 | return; 24 | } 25 | 26 | $jobs = []; 27 | 28 | if (config('elogquent.remove_previous_duplicates')) { 29 | $jobs[] = new ProcessRemoveDuplicates( 30 | $modelClass, 31 | $modelKey, 32 | $changes->toArray(), 33 | ); 34 | } 35 | 36 | $jobs[] = new ProcessCreateEntry( 37 | $modelClass, 38 | $modelKey, 39 | $changes->toArray(), 40 | ); 41 | 42 | $limit = $this->getLimit($modelClass); 43 | if ($limit) { 44 | $jobs[] = new ProcessClearExceededLimit( 45 | $modelClass, 46 | $modelKey, 47 | $limit, 48 | ); 49 | } 50 | 51 | $this->dispatchJobs($jobs); 52 | } 53 | 54 | private function dispatchJobs(array $jobs): void 55 | { 56 | Bus::chain($jobs) 57 | ->onConnection(config('elogquent.queue.connection')) 58 | ->onQueue(config('elogquent.queue.queue')) 59 | ->delay(config('elogquent.queue.delay')) 60 | ->catch(function (Throwable $exception) { 61 | throw new ElogquentError($exception->getMessage()); 62 | }) 63 | ->dispatch(); 64 | } 65 | 66 | private function getLimit(string $modelClass): ?int 67 | { 68 | $limit = config('elogquent.changes_limit'); 69 | $limitPerModel = config('elogquent.model_changes_limit'); 70 | if (is_array($limitPerModel) && isset($limitPerModel[$modelClass])) { 71 | $limit = $limitPerModel[$modelClass]; 72 | } 73 | 74 | return $limit; 75 | } 76 | 77 | private function getChanges(array $changes): Collection 78 | { 79 | $included = config('elogquent.included_columns', []); 80 | $excluded = config('elogquent.excluded_columns', []); 81 | 82 | $changes = collect($changes); 83 | 84 | if (! empty($included)) { 85 | $changes = $changes->intersectByKeys(array_flip($included)); 86 | } 87 | if (! empty($excluded)) { 88 | $changes = $changes->diffKeys(array_flip($excluded)); 89 | } 90 | 91 | return $changes; 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /tests/Repositories/ElogquentDatabaseRepositoryTest.php: -------------------------------------------------------------------------------- 1 | create('SomeClass', 1, ['name' => 'Luis'], 1); 15 | 16 | $this->assertDatabaseHas('elogquent_entries', [ 17 | 'model_id' => 1, 18 | 'model_type' => 'SomeClass', 19 | 'column' => 'name', 20 | 'value' => 'Luis', 21 | ]); 22 | }); 23 | 24 | it('delete exceeded limit', function () { 25 | $modelClass = 'SomeClass'; 26 | $modelKey = '1'; 27 | 28 | ElogquentEntry::factory(2)->create([ 29 | 'model_id' => $modelKey, 30 | 'model_type' => $modelClass, 31 | ]); 32 | 33 | $sut = new ElogquentDatabaseRepository(); 34 | $sut->removeExceededLimit($modelClass, $modelKey, 1); 35 | 36 | $this->assertDatabaseCount('elogquent_entries', 1); 37 | }); 38 | 39 | it('delete duplicates', function () { 40 | $modelClass = 'SomeClass'; 41 | $modelKey = '1'; 42 | $column = 'name'; 43 | $value = 'Luis'; 44 | 45 | ElogquentEntry::factory(2)->create([ 46 | 'model_id' => $modelKey, 47 | 'model_type' => $modelClass, 48 | 'column' => $column, 49 | 'value' => $value, 50 | ]); 51 | 52 | $this->assertDatabaseCount('elogquent_entries', 2); 53 | 54 | $sut = new ElogquentDatabaseRepository(); 55 | $sut->removeChanges($modelClass, $modelKey, [$column => $value]); 56 | 57 | $this->assertDatabaseCount('elogquent_entries', 0); 58 | }); 59 | 60 | it('restore changes', function () { 61 | $column = 'name'; 62 | $value = 'foo'; 63 | 64 | $model = TestFakeModel::create(['name' => 'Luis']); 65 | 66 | $sut = new ElogquentDatabaseRepository(); 67 | $sut->restoreChanges($model, [$column => $value]); 68 | 69 | $this->assertDatabaseHas('fake_models', [ 70 | 'id' => $model->id, 71 | $column => $value, 72 | ]); 73 | }); 74 | 75 | it('fail create', function () { 76 | Schema::drop('elogquent_entries'); 77 | 78 | $sut = new ElogquentDatabaseRepository(); 79 | $sut->create(1, 1, [1 => 2]); 80 | 81 | })->throws(ElogquentDatabaseError::class, 'Error storing in database:'); 82 | 83 | it('fail remove changes', function () { 84 | Schema::drop('elogquent_entries'); 85 | 86 | $sut = new ElogquentDatabaseRepository(); 87 | $sut->removeChanges('Model', 1, ['name' => 'Luis']); 88 | 89 | })->throws(ElogquentDatabaseError::class, 'Elogquent remove changes error:'); 90 | 91 | it('fail remove exceded limit', function () { 92 | Schema::drop('elogquent_entries'); 93 | 94 | $sut = new ElogquentDatabaseRepository(); 95 | $sut->removeExceededLimit('Model', 1, 1); 96 | 97 | })->throws(ElogquentDatabaseError::class, 'Get the last model for remove duplicates error:'); 98 | 99 | it('fail restore changes', function () { 100 | $model = TestFakeModel::create(['name' => 'Luis']); 101 | $sut = new ElogquentDatabaseRepository(); 102 | $sut->restoreChanges($model, ['foo' => 'bar']); 103 | 104 | })->throws(ElogquentDatabaseError::class, 'Restore changes error:'); 105 | -------------------------------------------------------------------------------- /src/Repositories/ElogquentDatabaseRepository.php: -------------------------------------------------------------------------------- 1 | map(fn ($value, $column) => [ 25 | 'model_type' => $modelClass, 26 | 'model_id' => $modelKey, 27 | 'user_id' => $userId, 28 | 'column' => $column, 29 | 'value' => $value, 30 | 'created_at' => now(), 31 | ])->toArray(); 32 | 33 | ElogquentEntry::query() 34 | ->insert($inserts); 35 | }); 36 | } catch (Exception $e) { 37 | throw new ElogquentDatabaseError( 38 | "Elogquent storing model change error: {$e->getMessage()}" 39 | ); 40 | } 41 | } 42 | 43 | #[Override] 44 | public function removeChanges( 45 | string $modelClass, 46 | int $modelKey, 47 | array $changes, 48 | ): void { 49 | try { 50 | foreach ($changes as $column => $value) { 51 | ElogquentEntry::query() 52 | ->where('model_id', $modelKey) 53 | ->where('model_type', $modelClass) 54 | ->where('column', $column) 55 | ->where('value', $value) 56 | ->delete(); 57 | } 58 | } catch (Exception $e) { 59 | throw new ElogquentDatabaseError( 60 | "Elogquent remove changes error: {$e->getMessage()}" 61 | ); 62 | } 63 | } 64 | 65 | #[Override] 66 | public function removeExceededLimit(string $modelClass, int $modelKey, int $limit): void 67 | { 68 | try { 69 | $oldestElogquentEntryId = ElogquentEntry::query() 70 | ->where('model_id', $modelKey) 71 | ->where('model_type', $modelClass) 72 | ->offset($limit) 73 | ->limit(1) 74 | ->orderBy('id', 'desc') 75 | ->pluck('id') 76 | ->pop(); 77 | } catch (Exception $e) { 78 | throw new ElogquentDatabaseError( 79 | "Get the last model for remove duplicates error: {$e->getMessage()}" 80 | ); 81 | } 82 | 83 | if (empty($oldestElogquentEntryId)) { 84 | return; 85 | } 86 | 87 | ElogquentEntry::query() 88 | ->where('id', '<=', $oldestElogquentEntryId) 89 | ->where('model_id', $modelKey) 90 | ->where('model_type', $modelClass) 91 | ->delete(); 92 | } 93 | 94 | #[Override] 95 | public function restoreChanges(Model $model, array $changes): void 96 | { 97 | try { 98 | $model->update($changes); 99 | } catch (Exception $e) { 100 | throw new ElogquentDatabaseError( 101 | "Restore changes error: {$e->getMessage()}" 102 | ); 103 | } 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /config/elogquent.php: -------------------------------------------------------------------------------- 1 | env('ELOGQUENT_ENABLED', true), 14 | 15 | /* 16 | | 17 | |-------------------------------------------------------------------------- 18 | | User tracking 19 | |-------------------------------------------------------------------------- 20 | | Should store the user who changed the model? 21 | | 22 | */ 23 | 'store_user_id' => env('ELOGQUENT_STORE_USER_ID', true), 24 | 25 | /* 26 | |-------------------------------------------------------------------------- 27 | | Database Connection 28 | |-------------------------------------------------------------------------- 29 | | 30 | | Define the database connection to use for storing the change history. 31 | | 32 | */ 33 | 'database_connection' => env('ELOGQUENT_DATABASE_CONNECTION', config('database.default')), 34 | 35 | /* 36 | |-------------------------------------------------------------------------- 37 | | Included Columns 38 | |-------------------------------------------------------------------------- 39 | | 40 | | Specify the list of columns to track in the change history. 41 | | If empty, all model attributes will be tracked (except excluded ones). 42 | | 43 | */ 44 | 'included_columns' => [], 45 | 46 | /* 47 | |-------------------------------------------------------------------------- 48 | | Excluded Columns 49 | |-------------------------------------------------------------------------- 50 | | 51 | | Columns to exclude from change history. Useful for sensitive or irrelevant data. 52 | | 53 | */ 54 | 'excluded_columns' => [ 55 | 'password', 56 | 'remember_token', 57 | 'api_token', 58 | 'secret', 59 | 'token', 60 | 'updated_at', 61 | ], 62 | 63 | /* 64 | |-------------------------------------------------------------------------- 65 | | Remove Duplicate States 66 | |-------------------------------------------------------------------------- 67 | | 68 | | When enabled, it will automatically remove consecutive entries with identical 69 | | attribute values, keeping only the latest one, to avoid redundant logs. 70 | | 71 | */ 72 | 'remove_previous_duplicates' => env('ELOGQUENT_REMOVE_DUPLICATES', true), 73 | 74 | /* 75 | |-------------------------------------------------------------------------- 76 | | Global Changes Limit 77 | |-------------------------------------------------------------------------- 78 | | 79 | | Set a maximum number of total historical changes. 80 | | You can override this per model using "model_changes_limit". 81 | | 82 | */ 83 | 'changes_limit' => env('ELOGQUENT_CHANGES_LIMIT'), 84 | 85 | /* 86 | |-------------------------------------------------------------------------- 87 | | Model-specific Changes Limit 88 | |-------------------------------------------------------------------------- 89 | | 90 | | Set a limit on the number of change records per model. 91 | | If a model is not listed here, the global "changes_limit" will apply. 92 | | 93 | | Example: 94 | | 'model_changes_limit' => [ 95 | | \App\Models\Post::class => 100, 96 | | \App\Models\User::class => 10, 97 | | ], 98 | | 99 | */ 100 | 'model_changes_limit' => env('ELOGQUENT_MODEL_CHANGES_LIMIT', []), 101 | 102 | /* 103 | |-------------------------------------------------------------------------- 104 | | Elogquent Queue 105 | |-------------------------------------------------------------------------- 106 | | 107 | | Configure the queue settings for processing pending updates asynchronously. 108 | | You can customize the connection, delay, and queue name as needed. 109 | | 110 | */ 111 | 'queue' => [ 112 | 'delay' => env('ELOGQUENT_QUEUE_DELAY', 0), 113 | 'connection' => env('ELOGQUENT_QUEUE_CONNECTION', config('queue.default')), 114 | 'queue' => env('ELOGQUENT_QUEUE_QUEUE'), 115 | ], 116 | ]; 117 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 |

3 | Elogquent Logo 4 |

5 | 6 |

7 | PHP Version 8 | Latest Version 9 | Total Downloads 10 | Tests 11 | Lint 12 | Coverage 13 |

14 | 15 | --- 16 | 17 | **Elogquent** is a Laravel package that automatically tracks and stores all changes made to your Eloquent models. 18 | It provides a complete audit trail and allows restoring models to previous states with ease. 19 | 20 | ### Restore Preview 21 | 22 |

23 | RestoreChanges Animation 24 |

25 | 26 | --- 27 | 28 | ## Features 29 | 30 | - Automatic model change tracking 31 | - Configurable attribute inclusion/exclusion 32 | - Detailed change history per model 33 | - Restore previous model states 34 | - Duplicate change optimization 35 | - User attribution for changes 36 | - Supports queue-based processing 37 | 38 | --- 39 | 40 | ## Installation 41 | 42 | Install the package via Composer: 43 | 44 | ```bash 45 | composer require luissantiago/elogquent 46 | ``` 47 | 48 | Publish config and install: 49 | 50 | ```bash 51 | php artisan elogquent:install 52 | ``` 53 | 54 | Run the database migrations: 55 | 56 | ```bash 57 | php artisan migrate 58 | ``` 59 | 60 | --- 61 | 62 | ## Usage 63 | 64 | ### Add Trait to Your Model 65 | 66 | ```php 67 | use Elogquent\Traits\Elogquent; 68 | use Illuminate\Database\Eloquent\Model; 69 | 70 | class Post extends Model 71 | { 72 | use Elogquent; 73 | } 74 | ``` 75 | 76 | ### Access Change History 77 | 78 | ```php 79 | $post = Post::find(1); 80 | $changes = $post->allChanges; 81 | ``` 82 | 83 | ### Restore to a Previous State 84 | 85 | ```php 86 | $modelChange = ElogquentEntry::find(1); 87 | $modelChange->restore(); 88 | ``` 89 | 90 | Or use the artisan command: 91 | 92 | ```bash 93 | php artisan elogquent:restore-changes 94 | ``` 95 | 96 | --- 97 | 98 | ## Configuration 99 | 100 | Edit the `elogquent.php` config file for customization. 101 | 102 | ### Basic Settings 103 | 104 | | Option | Description | Default | 105 | |-----------------------|-----------------------------------------------------|-------------------| 106 | | `enabled` | Enable or disable Elogquent globally. | `true` | 107 | | `store_user_id` | Store the authenticated user's ID with each change. | `true` | 108 | | `database_connection` | The database connection used for change history. | Laravel default | 109 | 110 | ### Column Filtering 111 | 112 | | Option | Description | 113 | |--------------------|-----------------------------------------------------------------------------------------------------------------------------| 114 | | `included_columns` | Specific columns to track. If empty, all columns are tracked (except excluded). | 115 | | `excluded_columns` | Columns to ignore (e.g. sensitive fields). Default: `password`, `remember_token`, `api_token`, `secret`, `token`, `updated_at` | 116 | 117 | ### History Optimization 118 | 119 | | Option | Description | 120 | |------------------------------|--------------------------------------------------------------------| 121 | | `remove_previous_duplicates` | Prevent logging identical consecutive states. Keeps only the latest. | 122 | 123 | ### Change Limits 124 | 125 | | Option | Description | 126 | |-----------------------|-----------------------------------------------------------------------------------------------| 127 | | `changes_limit` | Global limit on total number of stored changes. | 128 | | `model_changes_limit` | Limit changes per model. Example: `'App\Models\Post::class' => 100` | 129 | 130 | ### Queue Settings 131 | 132 | | Option | Description | Default | 133 | |--------------------|-----------------------------------------------|-------------------------------------| 134 | | `queue.delay` | Delay (in seconds) before processing updates. | `0` | 135 | | `queue.connection` | Queue connection to use. | Laravel default (`queue.default`) | 136 | | `queue.queue` | Queue name for change jobs. | `null` | 137 | 138 | --- 139 | 140 | ## Contributing 141 | 142 | Please see [CONTRIBUTING](CONTRIBUTING.md) for details. 143 | 144 | --- 145 | 146 | ## License 147 | 148 | The MIT License (MIT). See [License File](LICENSE.md) for more information. 149 | 150 | --- 151 | 152 | ## Credits 153 | 154 | - [Luis Santiago](https://github.com/luissantiago) 155 | 156 | --- 157 | 158 | ## Support 159 | 160 | For support, open an issue in the GitHub repository or contact 161 | **soyluissantiagotorres@gmail.com** 162 | -------------------------------------------------------------------------------- /src/Commands/RestoreChangeCommand.php: -------------------------------------------------------------------------------- 1 | infoAndReturn('️⚙️ Please enable elogquent in config/elogquent.php'); 30 | } 31 | 32 | $modelType = $this->option('model'); 33 | $modelWithChanges = $this->modelsWithChanges(); 34 | if ($modelType && $modelWithChanges->doesntContain($modelType)) { 35 | return $this->infoAndReturn(sprintf('The model %s has no changes.', $modelType)); 36 | } 37 | 38 | if ($modelWithChanges->isEmpty()) { 39 | return $this->infoAndReturn('No models with changes found.'); 40 | } 41 | 42 | $modelType ??= select( 43 | label: 'Select the Model you want to restore:', 44 | options: $modelWithChanges->toArray(), 45 | scroll: 15, 46 | hint: 'You can use the arrow keys to navigate and press ', 47 | ); 48 | 49 | $modelId = $this->option('model-id') ?? text( 50 | label: 'Which model id would you like to restore?', 51 | placeholder: "Example: {$modelType} id 1", 52 | required: true, 53 | hint: 'Type the id of the model and press ', 54 | ); 55 | 56 | $currentModel = ElogquentEntry::query() 57 | ->where('model_type', $modelType) 58 | ->where('model_id', $modelId) 59 | ->first(); 60 | 61 | if (empty($currentModel)) { 62 | return $this->infoAndReturn(sprintf('🔍 Model %s with id %s not found', $modelType, $modelId)); 63 | } 64 | 65 | $columns = ElogquentEntry::query() 66 | ->distinct('column') 67 | ->select('column') 68 | ->where('model_type', $modelType) 69 | ->where('model_id', $modelId) 70 | ->pluck('column'); 71 | 72 | if ($columns->isEmpty()) { 73 | $message = sprintf('The model %s with id %s has no changes.', $modelType, $modelId); 74 | 75 | return $this->infoAndReturn($message); 76 | } 77 | 78 | $modelColumn = multiselect( 79 | label: 'Which model attributes you like to restore?', 80 | options: $columns, 81 | scroll: 15, 82 | hint: 'Use the arrow keys to navigate, press to select columns, and press to confirm.' 83 | ); 84 | 85 | if (empty($modelColumn)) { 86 | $message = sprintf('No changes selected for the model %s with id %s.', $modelType, $modelId); 87 | 88 | return $this->infoAndReturn($message); 89 | } 90 | 91 | $currentModel = ElogquentEntry::query() 92 | ->where('model_type', $modelType) 93 | ->where('model_id', $modelId) 94 | ->first() 95 | ->modelChanged; 96 | 97 | $changesToUpdate = []; 98 | foreach ($modelColumn as $column) { 99 | $currentValue = (string) $currentModel->getAttribute($column); 100 | $entries = ElogquentEntry::query() 101 | ->select(['id', 'value', 'created_at']) 102 | ->where('model_type', $modelType) 103 | ->where('model_id', $modelId) 104 | ->where('column', $column) 105 | ->orderBy('id', 'desc') 106 | ->limit(self::LIMIT_COLUMN_CHANGES) 107 | ->get() 108 | ->mapWithKeys(fn (ElogquentEntry $entry) => [$entry->getValue() => sprintf('%s (%s)', 109 | $this->formatWithColor('green', $entry->getValue()), 110 | $this->formatWithColor('white', $entry->getAttribute('created_at')), 111 | ), 112 | ]) 113 | ->toArray(); 114 | 115 | $changesToUpdate[$column] = select( 116 | label: "Which change for the column $column would you like to restore?", 117 | options: $entries, 118 | scroll: 15, 119 | hint: sprintf('The current value is: %s', $this->formatWithColor('red', $currentValue)), 120 | ); 121 | } 122 | 123 | $restore = confirm(label: 'Do you want to restore the changes?'); 124 | if ($restore) { 125 | ProcessRestoreChanges::dispatch($currentModel, $changesToUpdate) 126 | ->onConnection(config('elogquent.queue.connection')) 127 | ->onQueue(config('elogquent.queue.queue')) 128 | ->delay(config('elogquent.queue.delay')); 129 | 130 | $this->info('🎉 The model has been restored with the changes.'); 131 | } 132 | 133 | return self::SUCCESS; 134 | } 135 | 136 | private function modelsWithChanges(): Collection 137 | { 138 | return ElogquentEntry::query() 139 | ->select('model_type') 140 | ->distinct('model_type') 141 | ->orderBy('model_type') 142 | ->pluck('model_type', 'model_type'); 143 | } 144 | 145 | private function infoAndReturn(string $message): int 146 | { 147 | $this->info($message); 148 | 149 | return self::SUCCESS; 150 | } 151 | 152 | private function formatWithColor(string $color, string $text): string 153 | { 154 | return sprintf('%s', $color, $text); 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------