PHP code example of cndrsdrmn / eloquent-unique-attributes
1. Go to this page and download the library: Download cndrsdrmn/eloquent-unique-attributes library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
cndrsdrmn / eloquent-unique-attributes example snippets
return [
/**
* The prefix to add to the beginning of the generated unique value.
*/
'prefix' => '',
/**
* The suffix to add to the end of the generated unique value.
*/
'suffix' => '',
/**
* The separator to use between prefix, value, and suffix.
*/
'separator' => '_',
/**
* The maximum number of retries to generate a unique value before increasing the length.
*/
'max_retries' => 100,
/**
* The default length of the generated unique value.
*/
'length' => 8,
/**
* The format of the unique value.
*
* Supported options:
* - `numerify` - Replace `#` with random digits.
* - `lexify` - Replace `?` with random letters.
* - `bothify` - Replace `#` with digits and `?` with letters.
*
* @see https://github.com/cndrsdrmn/php-string-formatter
*/
'format' => 'bothify',
];
namespace App\Models;
use Cndrsdrmn\EloquentUniqueAttributes\HasEnforcesUniqueAttributes;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use HasEnforcesUniqueAttributes;
/**
* Define the unique attributes configuration.
*/
public function enforcedUniqueColumns(): array
{
return [
'barcode' => ['format' => 'numerify', 'separator' => '-'],
'sku' => ['prefix' => 'SKU', 'length' => 10],
];
}
}
use Illuminate\Support\Facades\Event;
Event::listen('eloquent.enforcing: App\Models\Product', function ($model, $event) {
// Returning any value here will skip the enforcement of unique attributes.
return true;
});
Event::listen('eloquent.enforced: App\Models\Product', function ($model, $status) {
// Execute logic after unique attributes are enforced.
if ($status) {
Log::info('Unique attributes enforced for model', ['model' => $model]);
}
});