Search code examples
laraveleloquent

Primary key not being set using Laravel Eloquent


I am trying to use a model to create a table and have the AcctId field be the primary key.

class account extends Model
{
    protected $connection = 'mysql';
    protected $table = 'accounts';
    protected $primaryKey = 'AcctId';
    public $incrementing = false;
    protected $keyType = 'string';
}

after I

php artisan migrate:fresh

My Migration

public function up(): void
{
    Schema::create('accounts', function (Blueprint $table) {
        $table->string('AcctId');
        $table->string('AccountName');
        $table->string('Address');
        $table->string('City');
        $table->string('State');
        $table->string('Zip');
        $table->timestamps();
    });
}

It is still not making AcctId the primary key. What am I missing?

enter image description here


Solution

  • I am happy to help you with this.

    When you create a table in Laravel and define a primary key, you need to specify it explicitly using the primary method. So in your case, it would be like this:

    $table->string('AcctId')->primary();
    

    Here is the full migration code:

    public function up(): void
    {
        Schema::create('accounts', function (Blueprint $table) {
            $table->string('AcctId')->primary();
            $table->string('AccountName');
            $table->string('Address');
            $table->string('City');
            $table->string('State');
            $table->string('Zip');
            $table->timestamps();
        });
    }
    

    After making the following changes, run the PHP artisan migrate and it should create the accounts table with AcctId as the primary key.