Francois LEJOLI
Francois LEJOLI

Reputation: 23

Is it possible to put composite keys in models in Laravel 8?

I want to create a Model with a composite primary key, is there any way to do this in Laravel 8?

Upvotes: 0

Views: 190

Answers (1)

Mohsen Nazari
Mohsen Nazari

Reputation: 1349

Yes, in your migration instead of using id use something like this:

Schema::create('users', function (Blueprint $table) {
        $table->primary(['name', 'email']);
});

more information on https://laravel.com/docs/8.x/migrations#available-index-types

When you want to access with Model, you can do something like this (since eloquent does not support composite find):

$user = User->where(['name' => $name, 'email' => $email])->first();

Upvotes: 1

Related Questions