├── .editorconfig ├── .gitignore ├── LICENSE ├── composer.json ├── phpunit.xml ├── readme.md ├── src ├── Exceptions │ └── UniqueCodeNotSupportedException.php ├── Providers │ └── LucgServiceProvider.php └── Traits │ └── HasUniqueCode.php └── tests ├── Foo.php ├── LucgTest.php └── TestCase.php /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = space 5 | indent_size = 4 6 | end_of_line = lf 7 | charset = utf-8 8 | trim_trailing_whitespace = true 9 | insert_final_newline = true 10 | 11 | [*.md] 12 | trim_trailing_whitespace = false 13 | 14 | [*.{yml,yaml}] 15 | indent_size = 2 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | .vscode 3 | .DS_Store 4 | .phpunit.result.cache 5 | /vendor 6 | composer.lock 7 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Mehmet Onur AKKAYA 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. 22 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "monurakkaya/laravel-unique-code-generator", 3 | "description": "Provides unique code for your models", 4 | "type": "library", 5 | "license": "MIT", 6 | "keywords": [ 7 | "laravel unique code", 8 | "code generator", 9 | "model", 10 | "eloquent", 11 | "laravel" 12 | ], 13 | "autoload": { 14 | "psr-4": { 15 | "Monurakkaya\\Lucg\\": "src/" 16 | } 17 | }, 18 | "autoload-dev": { 19 | "psr-4": { 20 | "Monurakkaya\\Lucg\\Tests\\": "tests/" 21 | } 22 | }, 23 | "authors": [ 24 | { 25 | "name": "Mehmet Onur Akkaya", 26 | "email": "monurakkaya@gmail.com" 27 | } 28 | ], 29 | "minimum-stability": "stable", 30 | "require": { 31 | "php": "^7.4 || ^8.0" 32 | }, 33 | "require-dev": { 34 | "orchestra/testbench": "^6.24 || ^7.0", 35 | "phpunit/phpunit": "^9.5" 36 | }, 37 | "extra": { 38 | "laravel": { 39 | "providers": [ 40 | "Monurakkaya\\Lucg\\Providers\\LucgServiceProvider" 41 | ] 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /phpunit.xml: -------------------------------------------------------------------------------- 1 | 2 | 13 | 14 | 15 | ./tests 16 | 17 | 18 | 19 | 20 | 21 | src 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # Laravel unique code generator 2 | Provides unique code for your Eloquent models 3 | 4 | 5 | ## INSTALLATION 6 | ``` 7 | composer require monurakkaya/laravel-unique-code-generator 8 | ``` 9 | 10 | ## USAGE 11 | ### The schema 12 | 13 | #### To create the column 14 | 15 | ``` 16 | // This will generate an unique string column named `code` 255 length which equivalent to $table->string('code', 255)->unique(); 17 | Schema::create('table', function (Blueprint $table) { 18 | ... 19 | $table->uniqueCode(); 20 | }); 21 | ``` 22 | 23 | #### To drop the column 24 | ``` 25 | Schema::table('table', function (Blueprint $table) { 26 | $table->dropUniqueCode(); 27 | }); 28 | ``` 29 | 30 | #### To use your own column just pass the parameters to override the default values 31 | ``` 32 | // on create 33 | $table->uniqueCode('my_code', 'bigInteger', 32); // columnName, columnType, columnLength 34 | 35 | // on drop 36 | $table->dropUniqueCode('my_code'); 37 | ``` 38 | 39 | Using schema helper is optional. You can go on with your own definitions. 40 | 41 | ### The model 42 | 43 | Your model should use Monurakkaya\Lucg\HasUniqueCode trait to enable unique code functions: 44 | ``` 45 | use Monurakkaya\Lucg\HasUniqueCode; 46 | 47 | class Foo extends Model { 48 | use HasUniqueCode; 49 | } 50 | ``` 51 | 52 | 53 | and that's all. 54 | 55 | ``` 56 | $foo = Foo::create(['title' => 'Foo']); 57 | #attributes: array:10 [▼ 58 | "id" => 1 59 | "code" => "OF0EIL8B" 60 | "title" => "Foo" 61 | "created_at" => "2022-01-24 13:11:03" 62 | "updated_at" => "2022-01-24 13:11:03" 63 | ] 64 | ``` 65 | 66 | #### SETTINGS 67 | 68 | To change the column name just override the `uniqueCodeColumnName` method on your model 69 | ``` 70 | 71 | class Foo extends Model { 72 | use HasUniqueCode; 73 | 74 | protected static function uniqueCodeColumnName() 75 | { 76 | return 'my_code'; 77 | } 78 | } 79 | 80 | ``` 81 | 82 | ** Make sure your code column name to be equal to your column name. Default is `code` 83 | 84 | 85 | To change the code type just override the `uniqueCodeType` method on your model 86 | ``` 87 | 88 | class Foo extends Model { 89 | use HasUniqueCode; 90 | 91 | protected static function uniqueCodeType() 92 | { 93 | return 'numeric'; 94 | } 95 | } 96 | 97 | ``` 98 | 99 | Available types are `'random_uppercase', 'random_lowercase', 'uuid', 'numeric'`. Default is `random_uppercase` 100 | 101 | ** If you are going to use uuid, I recommend you to set column definition as uuid 102 | 103 | 104 | To change the code length just override the `uniqueCodeLength` method on your model 105 | ``` 106 | 107 | class Foo extends Model { 108 | use HasUniqueCode; 109 | 110 | protected static function uniqueCodeLength() 111 | { 112 | return 32; 113 | } 114 | } 115 | 116 | ``` 117 | 118 | ** Make sure your code length lte than column length. Default is `8` 119 | 120 | 121 | ## Tests 122 | 123 | To run the tests, execute the following from the command line, while in the project root directory: 124 | 125 | ```shell 126 | ./vendor/bin/phpunit 127 | ``` 128 | 129 | 130 | -------------------------------------------------------------------------------- /src/Exceptions/UniqueCodeNotSupportedException.php: -------------------------------------------------------------------------------- 1 | addColumn($columnType, $columnName, compact('length'))->unique(); 15 | }); 16 | 17 | Blueprint::macro('dropUniqueCode', function ($columnName = 'code') { 18 | return $this->dropColumn($columnName); 19 | }); 20 | } 21 | } -------------------------------------------------------------------------------- /src/Traits/HasUniqueCode.php: -------------------------------------------------------------------------------- 1 | isDirty(self::uniqueCodeColumnName())) { 38 | $model->{self::uniqueCodeColumnName()} = self::generateCode($model); 39 | } 40 | }); 41 | } 42 | 43 | /** 44 | * @throws UniqueCodeNotSupportedException 45 | */ 46 | public static function generateCode(Model $model) 47 | { 48 | self::checkUniqueCodeIsSupported(); 49 | $code = self::{'generate'. Str::studly(self::uniqueCodeType()).'UniqueCode'}(); 50 | 51 | $query = self::query(); 52 | 53 | if (in_array(SoftDeletes::class, class_uses_recursive($model))) { 54 | $query->withTrashed(); 55 | } 56 | 57 | if ($query->where(self::uniqueCodeColumnName(), $code)->exists()) { 58 | return self::generateCode($model); 59 | } 60 | return $code; 61 | } 62 | 63 | protected static function generateRandomUppercaseUniqueCode() 64 | { 65 | return Str::upper( 66 | Str::random( 67 | self::uniqueCodeLength() 68 | ) 69 | ); 70 | } 71 | 72 | protected static function generateRandomLowercaseUniqueCode() 73 | { 74 | return Str::lower( 75 | Str::random( 76 | self::uniqueCodeLength() 77 | ) 78 | ); 79 | } 80 | 81 | protected static function generateNumericUniqueCode() 82 | { 83 | return random_int( 84 | pow(10, self::uniqueCodeLength() - 1), 85 | (pow(10, self::uniqueCodeLength()) - 1) 86 | ); 87 | } 88 | 89 | protected static function generateUuidUniqueCode() 90 | { 91 | return Str::uuid()->toString(); 92 | } 93 | 94 | protected static function uniqueCodeLength() 95 | { 96 | return 8; 97 | } 98 | 99 | protected static function uniqueCodeType() 100 | { 101 | return 'random_uppercase'; 102 | } 103 | 104 | protected static function uniqueCodeColumnName() 105 | { 106 | return 'code'; 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /tests/Foo.php: -------------------------------------------------------------------------------- 1 | assertNotNull($foo->code); 21 | } 22 | 23 | /** @test */ 24 | public function it_checks_soft_deletes_trait(): void 25 | { 26 | DB::enableQueryLog(); 27 | $model = new class () extends Foo { 28 | use SoftDeletes; 29 | }; 30 | 31 | $model::creating(function ( Model $m ) use ($model) { 32 | $logs = DB::getQueryLog(); 33 | $this->assertStringNotContainsString('deleted_at', $logs[0]['query']); 34 | }); 35 | 36 | $model::create(); 37 | 38 | DB::disableQueryLog(); 39 | } 40 | 41 | /** @test */ 42 | public function it_generates_code_with_given_length(): void 43 | { 44 | $class = new class extends Model { 45 | use HasUniqueCode; 46 | protected $table = 'foos'; 47 | public $timestamps = false; 48 | 49 | protected static function uniqueCodeLength() 50 | { 51 | return 11; 52 | } 53 | 54 | }; 55 | 56 | $foo = $class::create(); 57 | 58 | $this->assertSame(11, strlen($foo->code)); 59 | } 60 | 61 | /** @test */ 62 | public function it_generates_code_with_given_type_numeric(): void 63 | { 64 | $class = new class extends Model { 65 | use HasUniqueCode; 66 | protected $table = 'foos'; 67 | public $timestamps = false; 68 | 69 | protected static function uniqueCodeType() 70 | { 71 | return 'numeric'; 72 | } 73 | 74 | }; 75 | 76 | $foo = $class::create(); 77 | 78 | $this->assertIsNumeric($foo->code); 79 | } 80 | 81 | /** @test */ 82 | public function it_generates_code_with_given_type_uuid(): void 83 | { 84 | $class = new class extends Model { 85 | use HasUniqueCode; 86 | protected $table = 'foos'; 87 | public $timestamps = false; 88 | 89 | protected static function uniqueCodeType() 90 | { 91 | return 'uuid'; 92 | } 93 | 94 | }; 95 | 96 | $foo = $class::create(); 97 | 98 | $this->assertTrue((Str::isUuid($foo->code))); 99 | } 100 | 101 | /** @test */ 102 | public function it_throws_error_with_undefined_type(): void 103 | { 104 | $class = new class extends Model { 105 | use HasUniqueCode; 106 | protected $table = 'foos'; 107 | public $timestamps = false; 108 | 109 | protected static function uniqueCodeType() 110 | { 111 | return 'xxx'; 112 | } 113 | 114 | }; 115 | 116 | $this->assertThrows(fn () => $class::create(), UniqueCodeNotSupportedException::class); 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /tests/TestCase.php: -------------------------------------------------------------------------------- 1 | setUpDatabase(); 15 | } 16 | 17 | protected function setUpDatabase(): void 18 | { 19 | $this->app['db']->connection()->getSchemaBuilder()->create('foos', function (Blueprint $table) { 20 | $table->id(); 21 | $table->uniqueCode(); 22 | $table->softDeletes(); 23 | }); 24 | 25 | for ($i = 0; $i < 10; $i++) { 26 | Foo::create(); 27 | } 28 | } 29 | 30 | protected function getPackageProviders($app): array 31 | { 32 | return [ 33 | 'Monurakkaya\Lucg\Providers\LucgServiceProvider', 34 | ]; 35 | } 36 | } 37 | --------------------------------------------------------------------------------