eg-mohamed / model-reference
Easily Generate Reference Number with customization to your model
Requires
- php: ^8.3
- illuminate/contracts: ^10.0||^11.0||^12.0
- spatie/laravel-package-tools: ^1.92.4
Requires (Dev)
- larastan/larastan: ^2.9||^3.3.1
- laravel/pint: ^1.22
- nunomaduro/collision: ^8.8.0||^7.10.0
- orchestra/testbench: ^10.2.1||^9.0.0||^8.22.0
- pestphp/pest: ^3.8.2
- pestphp/pest-plugin-arch: ^3.1.1
- pestphp/pest-plugin-laravel: ^3.2
- phpstan/extension-installer: ^1.4.3||^2.0
- phpstan/phpstan-deprecation-rules: ^1.1||^2.0.1
- phpstan/phpstan-phpunit: ^1.3||^2.0.6
README
This package makes it easy to generate unique reference numbers for your Laravel models.
Installation
- Install the package via composer:
composer require eg-mohamed/model-reference
- Publish the configuration file:
php artisan vendor:publish --tag="model-reference-config"
Usage
1. Add the reference column to your migration
Make sure your model's table has a column to store the reference:
Schema::create('orders', function (Blueprint $table) { $table->id(); $table->string('reference')->unique(); // Add this column to store references $table->timestamps(); });
2. Use the trait in your model
use MoSaid\ModelReference\Traits\HasReference; class Order extends Model { use HasReference; }
That's it! Now whenever you create a new record, it will automatically generate a reference:
$order = Order::create([ 'customer_id' => 1, 'total' => 99.99, // No need to specify the reference; it will be generated automatically ]); echo $order->reference; // Outputs something like "AB12CD"
Customization
You can customize how references are generated by adding properties to your model:
class Order extends Model { use HasReference; // Change the column name (default: 'reference') protected $referenceColumn = 'order_number'; // Set a prefix (e.g., ORD-123456) protected $referencePrefix = 'ORD'; // Set a suffix (e.g., ORD-123456-2023) protected $referenceSuffix = '2023'; // Change the length of the random part (default: 6) protected $referenceLength = 8; // Change the separator (default: '-') protected $referenceSeparator = '_'; // Change the characters used (default: alphanumeric) protected $referenceCharacters = '0123456789'; }
With the settings above, you'd get references like: ORD_12345678_2023
Global Configuration
You can also change the default settings for all models in the config/model-reference.php
file:
return [ 'column_name' => 'reference', 'length' => 6, 'prefix' => '', 'suffix' => '', 'separator' => '-', 'characters' => '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' ];
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security Vulnerabilities
Please review our security policy on how to report security vulnerabilities.
Credits
License
The MIT License (MIT). Please see License File for more information.