Understand Many to many Relationships in laravel

push notification with laravel

Let’s imagine a good example for many-to-many relationships. Well, the books/categories relationship is perfect. In fact, imagine Twenty Thousand Leagues Under the Sea, Jules Verne.

It is not only an adventure novel but also a classic. So, you will need to classify it under two separate categories: Classics and Adventure. Our library could also contain Journey to the Center of the Earth, another classic, but also an other adventure novel. Same thing!

As you can see, this time a many-to-many relationship is absolutely necessary. Let’s discover how Eloquent handles many-to-many relationships and how you can define them on models.

Here’s the code for our Book model:

  <?php namespace App;

  use IlluminateDatabaseEloquentModel;

  class Book extends Model {

    public function author()
    {
      return $this->belongsTo('AppAuthor');
    }

  }

The code for Category model is:

  <?php namespace App;

  use IlluminateDatabaseEloquentModel;

  class Category extends Model {

    //

  }


This time, we don’t have any directions or a possible inverse of a relationship.

Specifically, there are many books for many categories. So, the only method you need to use in this case is belongsToMany(). Use the method like this:

  <?php namespace App;

  use IlluminateDatabaseEloquentModel;

  class Book extends Model {

    public function author()
    {
      return $this->belongsTo('AppAuthor');
    }

    public function categories()
    {
      return $this->belongsToMany('AppCategory');
    }

  }

The other method is used as follows:

  <?php namespace App;

  use IlluminateDatabaseEloquentModel;

  class Category extends Model {

    public function books()
    {
      return $this->belongsToMany('AppBook');
    }

  }

Nothing else!

Let’s see what we need at a database level to handle this relation. As you can easily imagine, you will have to work with a pivot table in this case.

So, you will need to specify an appropriate extra table in your migration file, using the up() method, as follows:

  Schema::create('book_category', function(Blueprint $table)
  {
    $this->increments('id');

    $this->integer('book_id')->unsigned();
    $this->integer('category_id')->unsigned();

    $this->text('notes');

    $this->timestamps();
  });

You also have some conventions to follow. These are given here:

  • The table name is comprised of the name of the entities, which is singular, separated by an underscore
  • The table will contain two columns named after the interested entities (author_id and book_id)

Note

When you specify a relation, remember to use return before the appropriate method call. I know that’s a little obvious, but very often newbies forget it.

It’s really, really important that you follow the defined conventions. Laravel and Eloquent can change your workflow timeline significantly, but to get the result, you must follow conventions. The sooner you do it, the better you will feel.

About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

Pin It on Pinterest

Shares