Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

amitsolanki24_'s avatar

Composite key with laravel eloquent

How can I use composite key with laravel eloquent?

Table states
 primary key name,
primar key country,

When I use primary key as array, it's giving error.

 protected $primaryKey = ['name', 'country'];
0 likes
3 replies
Amaury's avatar

@amitsolanki24_ HI.

"Composite" Primary Keys

Eloquent requires each model to have at least one uniquely identifying "ID" that can serve as its primary key. "Composite" primary keys are not supported by Eloquent models. However, you are free to add additional multi-column, unique indexes to your database tables in addition to the table's uniquely identifying primary key.

https://laravel.com/docs/11.x/eloquent#composite-primary-keys

In your migration file, you have to add a column for the composite key:

$table->index(['name', 'country']);

// or

$table->primary(['name', 'country']);

1 like
amitsolanki24_'s avatar

@Amaury Hey, "Composite" primary keys are not supported by Eloquent models.

so how can I use composite primary key?

Amaury's avatar

@amitsolanki24_ Hi, I think you have the response from Laravel docs as I mentioned:

However, you are free to add additional multi-column, unique indexes to your database tables in addition to the table's uniquely identifying primary key.

In your migration file, you have to add a column for the composite key:

$table->index(['name', 'country']);

Now, a composite index has been added to your table which speed up your queries. This is a database optimisation, the queries remain the same.

You should read that article too: https://reneroth.xyz/composite-indices-in-laravel/

Please or to participate in this conversation.