Skip to content

Relations

Marco E edited this page Sep 7, 2020 · 4 revisions

Eloquent relationships

Database tables are often related to one another. For example, a blog post may have many comments, or an order could be related to the user who placed it. Eloquent makes managing and working with these relationships easy, and supports several different types of relationships.

Many-to-many relationship

  • In the User model, we need to specify that one meeting can be associated with many users. We do this by using a Many-to-many relationship. Many-to-many relationships are defined by writing a method that returns the result of the belongsToMany method:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The meetings that belong to the user.
     */
    public function meetings()
    {
        return $this->belongsToMany('App\Meeting');
    }
}
  • We also need to define the inverse of the relationship as one user can have many meetings. This means that we have to define the users method on the Meeting model:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Meeting extends Model
{
    /**
     * The users that belong to the meeting.
     */
    public function users()
    {
        return $this->belongsToMany('App\User');
    }
}
Clone this wiki locally