I am making this model in my laravel Application.
namespace AppModels;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
use IlluminateSupportStr;
class ApiKeys extends Model
{
use HasFactory;
const TABLE = 'api_keys';
protected $table = self::TABLE;
public static function boot()
{
parent::boot();
self::creating(function ($model) {
$model->identifier = Str::random(16);
});
}
}
And upon Identifier I want to ensure that contains a unique random string:
use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;
return new class extends Migration
{
public function up(): void
{
Schema::create('api_keys', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('identifier')->unique('unique_identifier');
$table->boolean('active');
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('api_keys');
}
};
But my application runs in multiple instances behind load balancer:
Would this cause not unique random strings be generated, in other words could Str::random(16)
(and the underlying function openssl_random_bytes
) generate non unique string if both executed from multiple instances?
In order to avoid this usually I prepend the hostname:
$model->identifier = gethostname()."_".Str::random(16);
But this makes the identifier look ugly or even expose some infrastructure information. How I could avoid this?