Using UUID for Models
Using UUIDs in your database tables is easier than it seems. Here are the steps you should take to ensure that October CMS works properly with UUID columns.
Migrations
The schema builder comes with a handy uuid
table column that we can use to place our UUIDs. You'll also need to append primary()
to ensure that the UUID becomes the primary key.
// updates/create_table.php
Schema::create('my_database_table', function (Blueprint $table) {
$table->uuid('id')->primary();
});
Models
In your models, set the $incrementing
variable to false
to ensure that the Model does not increment the value of the UUID.
Finally, automatically generating a UUID will require the Ramsey\Uuid\Uuid
. We'll be using this library because it already comes installed with Laravel, so there's no need to install any other UUID generator. Next, add the beforeCreate()
event method into your Model. The code to generate the UUID is:
use Ramsey\Uuid\Uuid;
class Test extends Model
{
public $incrementing = false;
public function beforeCreate()
{
$this->id = Uuid::uuid4()->toString();
}
}
You can learn more about the UUID library on GitHub.
There are no comments yet
Be the first one to comment