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

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including 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. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

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