I'm working on an ebook management system. Instead of an auto-incrementing integer primary key, I'm using UUIDs, which works fine:
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
$model->{$model->getKeyName()} = Uuid::generate()->string;
});
}
I also disabled PK incrementing on the model:
public $incrementing = false;
Now the EPUB standard suggests publishers to assign every book a UUID, if possible, so I thought it would be neat to use an existing UUID if the file provides it, otherwise generate a new one for the library.
So I added id
to the $fillable
array of my model and set the ID conditionally in my create
controller method:
if (array_key_exists('uuid', $epubMetaData)) {
$book->id = $epubMetaData['uuid'];
}
Then I populate the rest of my fields and $book->save()
the book. It ends up with a newly generated UUID, even if there is one in the $epubMetaData
array... So I suspect Laravel decides to ignore my ID. Is there anything I've missed?
Well, you aren't checking if the id is already set in your creating callback:
static::creating(function ($model) {
if (!$model->id) {
$model->id = Uuid::generate()->string;
}
});