├── .gitignore ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE.md ├── README.md ├── art └── logo.jpeg ├── composer.json ├── config └── trackable.php ├── migrations └── create_logs_table.php ├── phpunit.xml.dist ├── src ├── Models │ └── Log.php ├── ServiceProvider.php └── Traits │ └── Trackable.php └── tests ├── ModelTrackableTest.php ├── Models └── .gitkeep ├── TestCase.php └── config └── database.php /.gitignore: -------------------------------------------------------------------------------- 1 | build 2 | composer.lock 3 | docs 4 | vendor 5 | coverage 6 | .idea 7 | .phpunit.result.cache 8 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to `laravel-model-trackable` will be documented in this file 4 | 5 | ## 1.0.0 - 2020-11-26 6 | 7 | - initial release 8 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Contributions are **welcome** and will be fully **credited**. 4 | 5 | Please read and understand the contribution guide before creating an issue or pull request. 6 | 7 | ## Etiquette 8 | 9 | This project is open source, and as such, the maintainers give their free time to build and maintain the source code 10 | held within. They make the code freely available in the hope that it will be of use to other developers. It would be 11 | extremely unfair for them to suffer abuse or anger for their hard work. 12 | 13 | Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the 14 | world that developers are civilized and selfless people. 15 | 16 | It's the duty of the maintainer to ensure that all submissions to the project are of sufficient 17 | quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used. 18 | 19 | ## Viability 20 | 21 | When requesting or submitting new features, first consider whether it might be useful to others. Open 22 | source projects are used by many developers, who may have entirely different needs to your own. Think about 23 | whether or not your feature is likely to be used by other users of the project. 24 | 25 | ## Procedure 26 | 27 | Before filing an issue: 28 | 29 | - Attempt to replicate the problem, to ensure that it wasn't a coincidental incident. 30 | - Check to make sure your feature suggestion isn't already present within the project. 31 | - Check the pull requests tab to ensure that the bug doesn't have a fix in progress. 32 | - Check the pull requests tab to ensure that the feature isn't already in progress. 33 | 34 | Before submitting a pull request: 35 | 36 | - Check the codebase to ensure that your feature doesn't already exist. 37 | - Check the pull requests to ensure that another person hasn't already submitted the feature or fix. 38 | 39 | ## Requirements 40 | 41 | If the project maintainer has any additional requirements, you will find them listed here. 42 | 43 | - **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](https://pear.php.net/package/PHP_CodeSniffer). 44 | 45 | - **Add tests!** - Your patch won't be accepted if it doesn't have tests. 46 | 47 | - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. 48 | 49 | - **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option. 50 | 51 | - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. 52 | 53 | - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. 54 | 55 | **Happy coding**! 56 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Mouad ZIANI 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 all 13 | 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 THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | logo 3 |

4 |
5 | 6 | [![Latest Version on Packagist](https://img.shields.io/packagist/v/mouadziani/laravel-model-trackable.svg?style=flat-square)](https://packagist.org/packages/mouadziani/laravel-model-trackable) 7 | 8 | A laravel package that allows you to track and log nested changes applied on your (models, and their relations) using a **single Trait** 9 | 10 | ## Installation 11 | 12 | You can install the package via composer: 13 | 14 | ```bash 15 | composer require mouadziani/laravel-model-trackable 16 | ``` 17 | 18 | ## Simple Usage 19 | 20 | - Firstly you have to apply trackable trait on your model 21 | 22 | ``` php 23 | 24 | use LaravelModelTrackable\Traits\Trackable; 25 | 26 | class ModelName extends Model 27 | { 28 | use Trackable; 29 | 30 | // 31 | } 32 | ``` 33 | 34 | - In case you want to track the changes applied on your model's relationships, you need to add an attribute in your model called `$toBeLoggedRelations` which must contain an array of relationships like the example below 35 | ``` php 36 | 37 | use LaravelModelTrackable\Traits\Trackable; 38 | 39 | class ModelName extends Model 40 | { 41 | use Trackable; 42 | 43 | public $toBeLoggedRelations = ['relation1', 'relation2']; 44 | } 45 | ``` 46 | 47 | 48 | - Then, you can get an array that should contains all changes applied on your model after every update 49 | ``` php 50 | $model = ModelName::update([ 51 | ... 52 | ]); 53 | 54 | // Get list of changed attributes 55 | $model->getChangedAttributes(); 56 | ``` 57 | 58 | ## Disclaimer 59 | Currently this package can't track hasMany, ManyToMany or MorphMany relations 60 | 61 | ### Testing 62 | 63 | ``` bash 64 | composer test 65 | ``` 66 | 67 | ### Changelog 68 | 69 | Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently. 70 | 71 | ## Contributing 72 | 73 | Please see [CONTRIBUTING](CONTRIBUTING.md) for details. 74 | 75 | ### Security 76 | 77 | If you discover any security related issues, please email mouad.ziani1997@gmail.com instead of using the issue tracker. 78 | 79 | ## Credits 80 | 81 | - [Mouad ZIANI](https://github.com/mouadziani) 82 | - [All Contributors](../../contributors) 83 | 84 | 85 | ## Licence 86 | This package is [Treeware](https://treeware.earth). If you use it in production, then we ask that you [**buy the world a tree**](https://plant.treeware.earth/mouadziani/laravel-model-trackable) to thank us for our work. By contributing to the Treeware forest you’ll be creating employment for local families and restoring wildlife habitats. 87 | 88 | 89 | featured_repository 90 | -------------------------------------------------------------------------------- /art/logo.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mouadziani/laravel-model-trackable/2112c82033fc98d94703d84514c472de69e9f5f6/art/logo.jpeg -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "mouadziani/laravel-model-trackable", 3 | "description": "A laravel package that allows you to tracker and log nested changes applied on your models and their relations using a single Trait", 4 | "keywords": [ 5 | "mouadziani", 6 | "laravel-model-trackable" 7 | ], 8 | "homepage": "https://github.com/mouadziani/laravel-model-trackable", 9 | "license": "MIT", 10 | "type": "library", 11 | "authors": [ 12 | { 13 | "name": "Mouad ZIANI", 14 | "email": "mouad.ziani1997@gmail.com", 15 | "role": "Developer" 16 | } 17 | ], 18 | "require": { 19 | "illuminate/database": "~5.6.0|~5.7.0|~5.8.0|^6.0.0|^7.0.0|^8.0.0", 20 | "illuminate/events": "~5.6.0|~5.7.0|~5.8.0|^6.0.0|^7.0.0|^8.0.0", 21 | "illuminate/support": "^6.0 || ^7.0 || ^8.0" 22 | }, 23 | "require-dev": { 24 | "orchestra/testbench": "^6.0", 25 | "phpunit/phpunit": "^8.0" 26 | }, 27 | "autoload": { 28 | "psr-4": { 29 | "LaravelModelTrackable\\": "src/" 30 | } 31 | }, 32 | "autoload-dev": { 33 | "psr-4": { 34 | "LaravelModelTrackable\\Tests\\": "tests/" 35 | } 36 | }, 37 | "extra": { 38 | "laravel": { 39 | "providers": [ 40 | "LaravelModelTrackable\\ServiceProvider" 41 | ] 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /config/trackable.php: -------------------------------------------------------------------------------- 1 | 'logs', 9 | ]; 10 | -------------------------------------------------------------------------------- /migrations/create_logs_table.php: -------------------------------------------------------------------------------- 1 | bigIncrements('id'); 16 | $table->string('action')->nullable(); 17 | $table->text('description'); 18 | $table->nullableMorphs('subject', 'subject'); 19 | $table->nullableMorphs('causer', 'causer'); 20 | $table->json('properties')->nullable(); 21 | $table->timestamps(); 22 | }); 23 | } 24 | 25 | /** 26 | * Reverse the migrations. 27 | */ 28 | public function down() 29 | { 30 | Schema::dropIfExists(config('trackable.table_name')); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /phpunit.xml.dist: -------------------------------------------------------------------------------- 1 | 2 | 14 | 15 | 16 | ./tests 17 | 18 | 19 | 20 | 21 | ./src 22 | 23 | 24 | -------------------------------------------------------------------------------- /src/Models/Log.php: -------------------------------------------------------------------------------- 1 | 'collection', 17 | ]; 18 | 19 | public function __construct(array $attributes = []) 20 | { 21 | if (! isset($this->table)) { 22 | $this->setTable(config('trackable.table_name')); 23 | } 24 | 25 | parent::__construct($attributes); 26 | } 27 | 28 | public function subject(): MorphTo 29 | { 30 | return $this->morphTo(); 31 | } 32 | 33 | public function causer(): MorphTo 34 | { 35 | return $this->morphTo(); 36 | } 37 | 38 | public function changes(): Collection 39 | { 40 | if (! $this->properties instanceof Collection) { 41 | return new Collection(); 42 | } 43 | 44 | return $this->properties->only(['old', 'new']); 45 | } 46 | 47 | public function getChangesAttribute(): Collection 48 | { 49 | return $this->changes(); 50 | } 51 | 52 | public function scopeCausedBy(Builder $query, Model $causer): Builder 53 | { 54 | return $query 55 | ->where('causer_type', $causer->getMorphClass()) 56 | ->where('causer_id', $causer->getKey()); 57 | } 58 | 59 | public function scopeForSubject(Builder $query, Model $subject): Builder 60 | { 61 | return $query 62 | ->where('subject_type', get_class($subject)); 63 | } 64 | 65 | public static function log( 66 | Model $subject, 67 | int $subjectId, 68 | string $action, 69 | string $description = '', 70 | array $properties = [] 71 | ) { 72 | return self::create([ 73 | 'action' => $action, 74 | 'description' => $description, 75 | 'subject_type' => get_class($subject), 76 | 'subject_id' => $subjectId, 77 | 'causer_type' => get_class($auth), 78 | 'causer_id' => Auth::id(), 79 | 'properties' => $properties 80 | ]); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/ServiceProvider.php: -------------------------------------------------------------------------------- 1 | publishes([ 21 | __DIR__ . "/../migrations/create_logs_table.php" => database_path("/migrations/{$timestamp}_create_logs_table.php"), 22 | ], 'migrations'); 23 | } 24 | 25 | /** 26 | * Register the application services. 27 | * 28 | * @return void 29 | */ 30 | public function register() 31 | { 32 | // 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/Traits/Trackable.php: -------------------------------------------------------------------------------- 1 | getChanges(), static::UPDATED_AT)); 23 | self::$changedAttributes['old'] = Arr::only($model->getRawOriginal(), $changedFields); 24 | self::$changedAttributes['new'] = $model->changes; 25 | }); 26 | } 27 | 28 | /** 29 | * Get array of changed attributes 30 | * 31 | * @return array 32 | */ 33 | public function getChangedAttributes() 34 | { 35 | if( 36 | property_exists(self::class, 'toBeLoggedRelations') 37 | && 38 | is_array($this->toBeLoggedRelations) 39 | && 40 | !empty($this->toBeLoggedRelations) 41 | ) { 42 | $relationsChanges = []; 43 | foreach ($this->toBeLoggedRelations as $relation) { 44 | $changes = $this->{$relation}->getChangedAttributes(); 45 | if(Arr::has($changes, ['old', 'new'])) { 46 | $relationsChanges['old'] = $changes['old']; 47 | $relationsChanges['new'] = $changes['new']; 48 | } 49 | } 50 | 51 | return array_merge_recursive(self::$changedAttributes, $relationsChanges); 52 | } 53 | 54 | return self::$changedAttributes; 55 | } 56 | 57 | /** 58 | * Method to log an action 59 | * 60 | * @param string $action 61 | * @param string $description 62 | * @return mixed 63 | */ 64 | public function log(string $action, string $description = '') 65 | { 66 | return Log::log($this, $this->id, $action, $description, $this->getChangedAttributes()); 67 | } 68 | 69 | /** 70 | * Logs relationship 71 | * @return Builder 72 | */ 73 | public static function logHistory(): Builder 74 | { 75 | return Log::forSubject(self::getModel()); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /tests/ModelTrackableTest.php: -------------------------------------------------------------------------------- 1 | assertTrue(true); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /tests/Models/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mouadziani/laravel-model-trackable/2112c82033fc98d94703d84514c472de69e9f5f6/tests/Models/.gitkeep -------------------------------------------------------------------------------- /tests/TestCase.php: -------------------------------------------------------------------------------- 1 | addConnection($config['sqlite']); 18 | $db->setAsGlobal(); 19 | $db->bootEloquent(); 20 | 21 | $this->migrate(); 22 | $this->seed(); 23 | } 24 | 25 | /** 26 | * Migrate the database. 27 | * 28 | * @return void 29 | */ 30 | protected function migrate() 31 | { 32 | DB::schema()->dropAllTables(); 33 | 34 | //TODO: create tables for testing 35 | } 36 | 37 | protected function seed() 38 | { 39 | //TODO: create fake records for testing 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /tests/config/database.php: -------------------------------------------------------------------------------- 1 | [ 5 | 'driver' => 'sqlite', 6 | 'database' => ':memory:', 7 | 'prefix' => '', 8 | ], 9 | ]; 10 | --------------------------------------------------------------------------------