Should eloquent's many-to-many pivot table enforce uniqueness accross the two id columns? Laravel 5

- 1 answer

Ad

I thought that eloquent would (by default) enforce uniqueness accross the two id columns when generating a simple pivot (many-to-many) table?

Or am I doing something wrong?

Appointment model

public function client()
{
    return $this->belongsToMany('App\Client')->withTimestamps();
}

Client model

public function appointment()
{
    return $this->belongsToMany('App\Appointment')->withTimestamps();
}

Migration

    $table->integer('appointment_id')->unsigned();
    $table->foreign('appointment_id')->references('id')->on('appointments')->onDelete('cascade');

    $table->integer('client_id')->unsigned();
    $table->foreign('client_id')->references('id')->on('clients')->onDelete('cascade');

    $table->timestamps();

If eloquent doesn't do it by default, I'll have to add the index manually:

    $table->unique(array('appointment_id', 'client_id'));
Ad

Answer

Ad

Eloquent can't enforce uniqueness accross the two id columns, because Eloquent is not responsible for the database schema/configuration.

Migrations are responsible for this stuff, so you have to define uniqueness in a migration.

Ad
source: stackoverflow.com
Ad