Ask Your Question
3

How can Laravel's UUID be utilized as the primary key?

asked 2022-10-06 11:00:00 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-05-05 22:00:00 +0000

pufferfish gravatar image

Laravel's UUID can be utilized as the primary key in the following way:

  1. First, you need to add the UUID package to your Laravel project by running the following command:
composer require ramsey/uuid
  1. You can create a migration to add a UUID column to your table and set it as the primary key. Here's an example:
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');
    }
}
  1. In your model, you need to define the UUID as the primary key:
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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-10-06 11:00:00 +0000

Seen: 10 times

Last updated: May 05 '21