jamesmills / eloquent-uuid

A Laravel Eloquent Model trait for adding and using a uuid with models
139 stars 14 forks source link

Generate migrations using command for Models with Trait #3

Closed divdax closed 1 year ago

divdax commented 5 years ago

Nice and simple package!

If i pull in this package on an existing project it would be cool to generate migrations to insert the new uuid column and update all rows where is a missing uuid. Maybe something like this:

php artisan uuid:make:migration Model1,Model2 [--after=id, --update]

--after (default: id)
--update optional. Generate uuids for all rows.
jamesmills commented 5 years ago

Hi @divdax I love this idea, thanks for your suggestion.

Is this something you would be willing to submit a PR for?

caiokawasaki commented 5 years ago

Another cool thing would be default key be set to Model binding...

I already have a trait to create my Uuids, but if your package had this option I would use it for sure!

My trait:

<?php

namespace App\Traits;

use Str;

trait Uuid
{
    public function getRouteKeyName()
    {
        return 'uuid';
    }

    public static function bootUuid()
    {
        static::creating(function ($model) {
            $model->uuid = Str::uuid();
        });
    }
}
divdax commented 5 years ago

@jamesmills i'll try to create a command. 😄

One more thing: When adding a uuid column on an existing table with rows, the uuid column has to be nullable, otherwise you get an unique error.

Schema::table('users', function (Blueprint $table) {
    $table->uuid('uuid')->nullable()->unique()->after('id');
});

@caiokawasaki There is already a HasUuidTrait but without getRouteKeyName().

jamesmills commented 5 years ago

@divdax I actually liked your idea of

--update optional. Generate uuids for all rows.

What we might have to do is look to see if we are adding the UUID column to an empty table. If we are then everything will be OK. If we are adding the UUID to a table which already has rows then we would need to create it as nullable and then create a load of UUID's for the rows in the database and then remove the nullable. All this could probably be done programmatically and without the need for the --update option. It could just work it out by default.