Composite primary and foreign keys in Laravel

By Faramarz Salehpour
Colourful keys aligned on a surface
Composite keys include more than one attribute

Warning: Use of composite keys is strongly discouraged. Please consider reading the first comment by Shihan and also this stack overflow question for more details.

According to the definition of composite key in Database Systems book:

... it might take more than a single attribute to define functional dependence; that is, a key may be composed of more than one attribute. Such a multiattribute key is known as a composite key.

Does Laravel support them? Of course it does ...

Composite primary key

To define a composite primary key you just need to pass an array containing the attributes of the composite key. The order of the attributes in the arrays is the order of it in the key:

Schema::create('module_student', function(Blueprint $table)
{
    $table->integer('module_id');
    $table->integer('student_id');

    $table->primary(array('module_id', 'student_id')); 
});

Here we created a primary key which includes two attributes module and student in that order. It has been very elegant so far, which is the usual trend with Laravel.

Composite foreign key

Foreign keys also follow the same style. When you need to use the primary key defined above as a foreign key in another table you do it like so:

Schema::create('codes', function(Blueprint $table)
{
    $table->increments('id');
    $table->integer('module_id')->unsigned();
    $table->integer('student_id')->unsigned();

    $table
        ->foreign(array('module_id', 'student_id'))
        ->references(array('module_id', 'student_id'))
        ->on('module_student');
});