1. Go to this page and download the library: Download awaresoftware/custom-id 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/ */
awaresoftware / custom-id example snippets
use Aware\CustomId\Traits\HasCustomId;
use Illuminate\Database\Eloquent\Model;
class Event extends Model
{
use HasCustomId;
// Optional: Override if your config key differs from class name
protected function getCustomIdType(): string
{
return 'event'; // Default is strtolower(class_basename(static::class))
}
// Optional: Provide custom configuration
protected function getCustomIdConfig(): ?array
{
return [
'length' => 6,
'prefix' => 'EVT-',
];
}
}
Schema::create('events', function (Blueprint $table) {
$table->string('id', 10)->primary(); // Adjust length for prefix + ID length
// ... other columns
});
return [
// Character set (removes ambiguous characters by default)
'character_set' => 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789',
// Maximum generation attempts before throwing exception
'max_attempts' => 10,
// Default ID length (when not specified by model)
'default_length' => 8,
// Default prefix
'default_prefix' => '',
];
protected function getCustomIdConfig(): ?array
{
return [
'length' => 8, // ID length (excluding prefix)
'prefix' => 'ORDER-', // Prefix for the ID
'character_set' => 'ABC123', // Custom character set
'max_attempts' => 20, // Override max retry attempts
];
}
use Aware\CustomId\Traits\HasCustomId;
class User extends Authenticatable
{
use HasCustomId;
protected function getCustomIdConfig(): ?array
{
return config('custom-id.users');
}
}
use Illuminate\Database\Eloquent\SoftDeletes;
class Event extends Model
{
use HasCustomId, SoftDeletes;
// IDs from soft-deleted records won't be reused
}
use Aware\CustomId\Exceptions\CustomIdGenerationException;
try {
$model = MyModel::create($data);
} catch (CustomIdGenerationException $e) {
echo $e->modelType; // "my_model"
echo $e->attempts; // 10
echo $e->getMessage(); // "Failed to generate unique ID for my_model after 10 attempts"
}
use InvalidArgumentException;
try {
$model = MyModel::create($data);
} catch (InvalidArgumentException $e) {
// "ID length must be at least 1 for [my_model], got [0]."
// "Character set must contain at least 2 characters for [my_model]."
// "Max attempts must be at least 1 for [my_model], got [0]."
}