1- User table, make id uuid type.
No problem
php artisan migrate:refresh
But this error
php artisan db:seed
Error : ("SQLSTATE[HY000]: General error: 1364 Field 'id' doesn't have a default value")
2- Also companies want to be randomly distributed to users. In the user table, uuid type will be held in the user_id column.
Thank you from now...
User Model :
use UsesUuid;
protected $fillable = ['name', 'email', 'password', 'role', 'slug',];
protected $hidden = ['password', 'remember_token',];
protected $casts = ['email_verified_at' => 'datetime',];
public function companies()
{
return $this->hasMany('App\Company', 'user_id', 'id');
}
UsesUuid trait:
protected static function boot()
{
parent::boot();
static::creating(function ($post) {
$post->{$post->getKeyName()} = (string)Str::uuid();
});
}
public $incrementing = false;
public function getKeyType()
{
return 'string';
}
Users migration:
Schema::create('users', function (Blueprint $table) {
$table->uuid('id')->primary()->unique();
$table->string('name',100);
$table->string('email',100);
$table->timestamp('email_verified_at')->nullable();
$table->string('password',100);
$table->string('role',20)->nullable();
$table->string('slug',100);
$table->rememberToken();
$table->timestamps();
$table->softDeletes();
});
Companies migration:
Schema::create('companies', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('user_id',36);
$table->string('name', 100);
$table->timestamps();
$table->softDeletes();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
User factory:
$name = $faker->name;
return [
'id' => Str::uuid(),
'name' => $name,
'email' => $faker->unique()->safeEmail,
'email_verified_at' => now(),
'password' => Hash::make(123), // password
'remember_token' => Str::random(10),
'role' => 'user',
'slug' => Str::slug($name),
];
Company factory:
$name = $faker->company;
return [
'user_id' => Str::uuid(),
'name' => $name,
];
DatabaseSeeder :
factory(App\User::class, 5)->create();
factory(App\Company::class, 1500)->create();
modify your trait like this:
static::creating(function ($post) {
empty($post->{$post->getKeyName()}) && $post->{$post->getKeyName()} = (string)Str::uuid();
});
there is no need to make UUID unique, in your migration, because it is already!
$table->uuid('id');
$table->primary('id');
and factory must create primary UUID itself, don't add it yourself
I think with these changes, seeder must run successfully