How can I set string as primary key and not the default id in laravel-9 & php artisan migrate doesnt read the correspondence model class when migrate

Viewed 45

This is my migration table schema

    public function up()
    {
        Schema::create('ip_users', function (Blueprint $table) {
            $table->id('user_id',10);
            $table->string('user_uuid_id',60);
            $table->string('user_name',30);
            $table->string('user_email',30);
            $table->string('user_password',100);
            $table->boolean('user_active');
            $table->timestamp('user_date_created')->useCurrent();
            $table->timestamp('user_date_modified')->useCurrent();
            $table->comment("Registered user's credentials");
        });
    }

Below is my correspondence model for the migration table

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class IPUsers extends Model
{
    use HasFactory;

    /* Our own defined primay key */
    protected $table = 'ip_users';
    public $incrementing = false;
    protected $primaryKey = 'user_PK_id'; 

    /* To tell the eloquent model that our PrimaryKey type is not an integer*/
    protected $keyType = 'string';
}

When I do php artisan migrate the schema is stored like user_id as the primary key but I want user_uuid_id to be the primary key. Why doesn't the migration read the IPUsers model before migration or the migration doesn't work that way?

If model has another purpose what is it?

If migration doesn't work like that, then How can I set PK to my own column rather than the default id's?

I have read in laracasts that the laravel doesn't implement the set custom owned PK. What is the solution for this?

1 Answers

Simply add primary() to uuid field.

$table->string('user_uuid_id',60)->primary();
Related