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?
To disable auto incrementing (and therefore the management of your id column by Laravel), you can add a public $incrementing property to your model and set it to false:
public $incrementing = false;
You can also set a protected $primaryKey property in your model to override the default id column’s name:
protected $primaryKey = 'uuid';
Of course if your column is named “id”, you don’t have to do that.