Sunday, November 17, 2024
Google search engine
HomeLanguagesLaravel 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

RELATED ARTICLES

Most Popular

Recent Comments