In this tutorial you will learn about the Laravel Many to Many Relationship Example and its application with practical example.
In this Laravel many to many relationship example tutorial.I’ll show you how to implement and use many to many relationship along with the inverse of the many to many relationship.
Laravel Many to Many Relationship Example
In laravel using belongsToMany() method, you can define many to many relationship in laravel eloquent models. Then you can insert, update and delete data from table using many to many relationship in laravel.
Laravel Eloquent Many to Many Relationship Example
In this example we will demonstrate the implementation of Many to Many Relationship using two tables posts and tags. In this relationship each of the post can have many tags and each of the tag can be associated with many posts.
Now, lets understand how to define many to many relationships, Using belongsToMany() method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Post extends Model { ... public function tags() { return $this->belongsToMany('App\Tag'); } } |
Now, you can access the tags in the post model as follow:
1 2 3 4 5 |
$post = App\Post::find(8); foreach ($post->tags as $tag) { //do something } |
The inverse of Many to Many Relationship Example
In Laravel, the inverse relationship of a many to many relationships can be defined using belongsToMany method on the reverse model.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Tag extends Model { public function posts() { return $this->belongsToMany('App\Post'); } } |
Now you can access the post in the tag model as follow:
1 2 3 4 5 |
$tag = App\Tag::find(8); foreach ($tag->posts as $post) { //do something } |