In this article, we will learn how to create many to many relationshi between the two models using laravel web app. This is a little more complicated than one to one and one to many relationships. But don’t worry, let’s make an example here of how to create the simplest way relationship between two simple models so that we can understand.
When designing a database structure, you will know that some tables are related to each other. For example, in a blog application, Multiple Categories have Multiple Products, and an inverse relationship will be Multiple Products belongs to Multiple Categories. In MySQL database tables, we add the id of one table to another table, So, what we can do is that, when we go to a particular category, we need to display all the Products and Same, when we see the particular Product, we need to display all the Categories that belong to that specific Product.
Laravel offers a chic relationship that provides powerful query builders. In Laravel, chic relationships are defined in model classes. Laravel offers easy ways to build common relationships
Step 1 : Create Migrations
Now we have to create migration of "posts" and "categories" table. we will also add foreign key with posts table. so let's create like as below code
create_categories_table migration:
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string("name");
$table->timestamps();
});
create_post_table migration:
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string("title");
$table->string("description");
$table->timestamps();
});
Many-to-many relations require an intermediary pivot table to manage the relationship.
create_post_category_table migration:
Schema::create('post_category', function (Blueprint $table) {
$table->increments('id');
$table->integer('category_id')->unsigned();
$table->integer('post_id')->unsigned();
$table->timestamps();
});
Now, migrate using the following command.
php artisan migrate
Step 2 : Create Models with Many To Many relationships
Here, we will create a post and category model. We will also use the "belongsToMany()" methods to connect both models.
Goto App\Models\Post.php and edit bellow code
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Models\Category;
class Post extends Model
{
/**
* Get the comments for the blog post.
*/
public function categories()
{
return $this->belongsToMany(Category::class);
}
}
Pas second paramete for particuler filed
return $this->belongsToMany(Category::class, 'category_id');
Also, the same for the categories relationship. Goto App\Models\Category.php and edit bellow code
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Models\Post;
class Category extends Model
{
/**
* Get the posts for the blog post.
*/
public function posts()
{
return $this->belongsToMany(Post::class);
}
}
Now, if your pivot table also has some additional fields that are needed when you retrieve relationship data, you need to specify them when defining the relationship
return $this->belongsToMany(Post::class)->withPivot('active', 'created_at');
Step 3 : Create Controller
Now, we have 10 categories. So, we create a product and assign the two categories to one Product.
Goto app/Http/Controllers/PostController.php if no have a PostController.php Controller then mack bellow command
php artisan make:controller PostController
The then next edit below code with create function
PostController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;
use App\Models\Category;
class PostController extends Controller
{
/**
* create a product with 2 category.
*
*/
public function create(Request $request)
{
$post = new Post;
$post->title = 'many to many relationship in laravel';
$post->description = 'many to many relationship in laravel web applictions';
$post->save();
$category = Category::find([2, 4]);
$post->categories()->attach($category);
dd('Success');
}
}
show function
/**
* Get categories.
*
*/
public function show()
{
$categories = Post::find(1)->categories;
dd($categories);
}
Remove Item
/**
* Remove categories for a post.
*
*/
public function delete()
{
$post = Post::find(1);
$category = Category::find(3);
$post->categories()->detach($category);
}
I hope this will help you to understand many to many relationship in laravel app.