Код: Выделить всё
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
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);
});
}
}
Код: Выделить всё
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
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');
}
};
[img]https:// i.sstatic.net/VCm4KQct.png[/img]
Не приведет ли это к созданию уникальных случайных строк, другими словами, может ли Str::random(16) (и базовая функция openssl_random_bytes) генерирует неуникальную строку, если оба выполняются из нескольких экземпляров?
Чтобы избежать этого, я обычно добавляю имя хоста:
Код: Выделить всё
$model->identifier = gethostname()."_".Str::random(16);
Подробнее здесь: https://stackoverflow.com/questions/790 ... -app-isnta
Мобильная версия