Laravel 10 Many to Many Relationship Example

Laravel 10 Many to Many Relationship Example

Laravel 10 many to many relationship example; In this tutorial, you will learn laravel many to many relationship with examples.

Using belongsToMany() method, you can define many to many relationship in laravel eloquent models. And you can also insert, update and delete records from database table using many to many relationship in laravel

Laravel Eloquent Many to Many Relationship Example

In this example, you will see two tables name posts and tags.

Each post has many tags and each tag can have many posts.

To define many to many relationships, Using belongsToMany() method:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
   ...
    public function tags()
    {
        return $this->belongsToMany('App\Tag');
    }
}

To access the tags in the post model as follow:

$post = App\Post::find(8);

 foreach ($post->tags as $tag) {
    //do something
 }

The inverse of Many to Many Relationship Example

The inverse of a many to many relationships can be defined by simply calling the similar belongsToMany method on the reverse model. We can illustrate that by defining posts() method in Tag model as:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Tag extends Model
{
    public function posts()
    {
        return $this->belongsToMany('App\Post');
    }
}

To access the post in the tag model as follow:

$tag = App\Tag::find(8);

 foreach ($tag->posts as $post) {
     //do something
  }

Conclusion

In this tutorial, you have learned define many to many relationships and as well as how to use it.

Recommended Laravel Tutorials

Recommended:-Laravel Try Catch

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

Your email address will not be published. Required fields are marked *