Many to Many relationship structure in Laravel 7 php?

Could you please explain many to many relationship in laravel with table structure and code using an example?

To establish Many to Many relation, laravel has given a way by creating an intermediary table that is called pivot table. It is a very simple table containing two foreign keys of related tables (Models). We can understand this relation easily with an example as stated below.

 

We have two entities Category and Post. A category may belongs to many posts and a post may belongs to many categories. Lets start step by step.

1- Create a model and migration.

 

php artisan make:model Category -m

php artisan make:model Post -m

It will create posts and categories tables, and models together.

Migration of Category:

Schema::create('categories', function (Blueprint $table) {

            $table->increments('id');

            $table->string('title');

            $table->text('description');

        });

 

Migration of Post:

     public function up()

    {

        Schema::create('posts', function (Blueprint $table) {

            $table->increments('id');

            $table->string('title');

            $table->text('description');

            $table->tinyInteger('status')->default(1);

            $table->string('slug');

        });

    }

 

After completing the migration file run below command to create tables in database.

php artisan migrate

 

What is the way to create a Pivot table in Laravel?

The name of the pivot table should consist of singular names of both tables, separated by underscore symbols, and these names should be arranged in alphabetical order, so we have to have category_post, not post_category.

To create a pivot table, we can create the simple migration with artisan make:migration or use the community package called Laravel 5 Generators Extended where we have the command artisan make:migration:pivot.

Pivot table fields: by default, there should be only two fields – the foreign key to each of the tables, in our case category_id and post_id. You can insert more fields if you need, then you need to add them to the relationship assignment.

 

So as per the rules above Pivot table has these columns.

id

category_id

post_id

 

Migration of Pivot table:

public function up()

    {

        Schema::create('category_post', function (Blueprint $table) {

            $table->increments('id');

            $table->integer('category_id')->unsigned();

            $table->integer('post_id')->unsigned();

        });

    }

 

Now run  php artisan migrate

 

Now we will define many to many relationship in models.

 

namespace App;

use Illuminate\Database\Eloquent\Model;

use App\Post;

 

class Category extends Model

{

    protected $table = 'categories';

    public function posts(){

        return $this->belongsToMany(Post::class);

    }

}

 

And 

 

namespace App;

 

use Illuminate\Database\Eloquent\Model;

use App\Category;

 

class Post extends Model

{

    protected $table = 'posts';

    

    public function categories(){

        return $this->belongsToMany(Category::class);

    }   

}

 

Now in controller we can create and assign categories using below code.

 

namespace App\Http\Controllers;
use App\Category;
use App\Post;

use Illuminate\Http\Request;

class PostController extends Controller
{
    public function create(Request $request)
    {
        $post = new Post;
        $post->title = 'God of War';
        $post->description = 'Test description';

        $post->save();

        $category = Category::find([3, 4]);
        $post->categories()->attach($category);

        return 'Success';
    }
}

 

To display the post and category write in controller.

public function show(Post $post)
{
   return view('post.show', compact('post'));
}

And in the blade template you can access categories by eager loading automatically.

<br /> // show.blade.php</p> <p><h2>Post title: </h2><br /> <p>{{ $post->name }} || ${{ money_format($post->price, 2) }}</p></p> <p><h3>Post Belongs to</h3></p> <p><ul><br />     @foreach($post->categories as $category)<br />     <li>{{ $category->title }}</li><br />     @endforeach<br /> </ul><br />

 

And to remove a particular category you can use below code.

 

public function removeCategory(Post $post)
{
        $category = Category::find(3);

        $post->categories()->detach($category);
        
        return 'Success';
}

 

 

This is the way to work on many to many relation using laravel. If you face any difficulty in understanding, feel free to contact.