Defining many to many relationships in laravel

In many to many relationships, an intermediate table is being shared between two models. For example, a course can have many schools and school can have many courses. To define this relationship, a new table course_school with tables fields as course_id and school_id are needed to store relationships between courses and schools.

Schools table
id, name

Courses Table
id, name

Course_School Table
id, course_id, school_id 

Many-to-many relationships are defined by writing belongsToMany method in model class. For example, let’s define schools method in course model.


namespace App;

use Illuminate\Database\Eloquent\Model;

class Course extends Model
{
    public function schools()
    {
        return $this->belongsToMany('App\School','course_schools','course_id', 'school_id');
    }
}

To get all schools related to course use schools method define in course model.

$course = Course::find(1);
$schools = $course->schools();
// by chaining it
$schools = Course::find(1)->schools();

In above example code, belongsToMany method get first argument App\School is the Model name in the relationship and the second argument course_schools is the intermediate table for joining relationship. If you leave empty second argument then eloquent will join two related model names in alphabetical order. Third and fourth arguments are customizing column names of keys for joining. These can leave empty as well but then eloquent will look for id column is both related models.

Author: Anees Ahmad

Anees Ahmad is a young co-founder, creative project manager and multi-talented web developer at Techstriders.