Laravel 5 belongsToMany() by Using Pivot Table Example

Relationship using pivot table in Laravel 5? A method, belongsToMany(), is a part of Eloquent ORM in Laravel 5. It connects between tables and it has many to many relationship. In order to use it, you must have two models three tables.

Model

  1. Model: Post
  2. Model: Image

Table

  1. Table: post containing id, title, and content fields
  2. Table: image containing id, url, and title fields
  3. Table (pivot table): image_post containing post_id and image_id fields

You have to be aware that the third table name must be alphabetical order of related model names as the documentation says. So, in this case we have two models Post and Image, thus the third table, or the pivot table, name has to be image_post. This fashion order is a must.

What are we going to do with the table relationship? First, we have to build logic behind it. Say you are building simple CMS that its content/post contains many images. Look at the post table fields it doesn’t have any relationship with image at all, either does the image table. Yes, post table is for posts, image table is for image. How do we link it? Using the third table image_post.

Logic First

Let’s imagine the simple database record of post table. You have a post title “How to Make Noise” *I love to make noise with a girl ..haha joking..* with three images inside and you post it. The first id of the post table would be 1 and the first three ids of the image table would be 1, 2, 3. So, there is a record in post table and three records in image table. Now, how to chain them? Use the image_post table is the best.

The image_post table or known as pivot table does contain post_id and image_id fields, this where the hero comes to rescue. The table has to be filled with three records. The records would be like this.

post_id image_id
1 1
1 2
1 3

Now if you make a second post with 2 image in it, the post_id would be 2 and image_id would be 4 and 5. So, the image_table would be.

post_id image_id
1 1
1 2
1 3
2 4
2 5

Now again, you add the image from the image table that has id = 2 as the first post has for your second post. The final table would be.

post_id image_id
1 1
1 2
1 3
2 4
2 5
2 2

Laravel 5 in Action

If the logic meets your need then you can go on. To do like what showed above, you have to modify your Post model.

class Post extends Model {

    public function images()
    {
        return $this->belongsToMany('App\Image', 'image_post', 'post_id', 'image_id');
        //return $this->belongsToMany('MyApplication\Models\Image'); this is where I put my models
    }

}

The App\Image is location of your Image model. Me myself using different folder for my models.

Add Record to Pivot Table

Still remember our pivot table name? Yes Barney! What is it? image_post table Barney! Good! Now this is the controller.

class PostController extends Controller {

...

	public function store($id)
	{
		$post = Post::find($id);
		$post->images()->attach($image_ids)
	}

...

}

The Post::find($id) means you have to find the post you want to edit or you want to store images in it. Then the $post->images()->attach($image_ids) is the way to create a record in image_post table. the $image_ids must be an array containing the id of images.

Now, for example if the $id = 7, and the $image_ids = array(2, 3, 5) then the table after the execution will be.

post_id image_id
7 2
7 3
7 5

I won’t show you how to create a post and image record in the database using the Laravel, you Google it! Don’t be lazy! Cheers!