I'm using ramsey/uuid
as primary key for all of my project tables. How can I disable auto-increment and allow roles
and permissions
primary key to be fillable? I have managed to do it on other tables but I'm stuck with these two.
Create a folder in app
called Traits
. In there, create a file Uuids.php
.
Add the following code to Uuids.php
;
<?php
namespace YourNamespace;
use Illuminate\Support\Str;
trait Uuids
{
/**
* Boot function from Laravel
*/
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
$model->incrementing = false;
$model->{$model->getKeyName()} = Str::uuid()->toString();
});
}
}
Then in your migration file, you should have something like:
$table->uuid('id')->primary();
to replace $table->increments('id');
Don't forget to use the Uuids trait like so in your models;
<?php
namespace YourNamespace;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
use Uuids;
protected $guarded = [''];
protected $casts = [
'id' => 'string',
];
...
Before modifying a column, be sure to add the doctrine/dbal
dependency to your composer.json file. The Doctrine DBAL library is used to determine the current state of the column and create the SQL queries needed to make the specified adjustments to the column:
composer require doctrine/dbal
Next you create a migration file;
php artisan make:migration change_primary_key_type_in_roles_table --table=roles
then in your migration file. You do this, eg.
public function up()
{
Schema::table('roles', function (Blueprint $table) {
$table->uuid('id')->change();
});
}
public function down()
{
Schema::table('roles', function (Blueprint $table) {
$table->increments('id')->change();
});
}
Don't forget to do composer dumpautoload
.
Hope this helps.
UPDATE: I wrote a blog post on how to achieve this here