Laravel's UUID can be utilized as the primary key in the following way:
composer require ramsey/uuid
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Ramsey\Uuid\Uuid;
class CreateUsersTable extends Migration
{
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->uuid('id')->primary()->default(Uuid::uuid4());
$table->string('name');
$table->string('email')->unique();
$table->string('password');
});
}
public function down()
{
Schema::dropIfExists('users');
}
}
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public $incrementing = false;
protected $primaryKey = 'id';
}
By setting $incrementing
to false, you tell Laravel not to automatically generate an incrementing ID, and by setting $primaryKey
to 'id', you tell it to use the UUID field as the primary key.
With this setup, Laravel will automatically generate a UUID value for each new record you create, and use it as the primary key.
Asked: 2022-10-06 11:00:00 +0000
Seen: 10 times
Last updated: May 05 '21