How to Save and Display Many-to-Many Relations in Laravel【belongsToMany】
Thank you for your continued support.
This article contains advertisements that help fund our operations.
Table Of Contents
⇨ Click here for the table of contents for Laravel articles
In this article, we will define many-to-many relations in Laravel models. We will cover how to save data in the intermediate table for many-to-many relationships and how to display the data.
What are Relations?
Relations refer to the relationship between data in different tables in a database.
In this example, storing user_id allows us to reference user data from the users table.
In Laravel, this can be easily implemented with a simple definition.
The content of this article is a summary of the official documentation
Verification Environment
Laravel 6
Table Design
We have a posts table and a tags table, and we'll discuss the scenario where posts are associated with multiple tags.
In simple terms, this means "I want to be able to add multiple hashtags."
In such cases, you need to use many-to-many relationships.
Intermediate Table is Required for Many-to-Many
The intermediate table in this case is the post_tag table.
The Intermediate Table Name Should be Singular_singular
First, the names of the tables you want to associate with the intermediate table should be connected with an underscore in singular form.
Since this is the intermediate table between the posts and tags tables, it should be named post_tag.
The Intermediate Table Name Should Start with the Earlier Alphabetically
Although I mentioned a-z order, what I meant was alphabetical order.
In this case, since 'p' in posts comes before 't' in tags alphabetically, the table name becomes post_tag.
If it were a table linking users and tags, 't' comes before 'u', so it would be named tag_user.
Define in the Model
No model is needed for the intermediate table.
Instead, you need to define in both the Posts table model and the Tags table model.
Model Post.php
public function tags()
{
return $this->belongsToMany('App\Tag');
}
Model Tag.php
public function posts()
{
return $this->belongsToMany('App\Post');
}
Make sure to define where the App\Post is located in your model (some might be in App\Models\Post).
Retrieving Related Data
To relate multiple tags to a post list, it's good to use 'with'.
Controller
use App\Post;
~~~~~~~~
public function index()
{
$posts = Post::with('tags')->get();
//dd($posts);
return view('home');
}
Next, for displaying.
Since there are multiple tags, we iterate over them using foreach.
Views
@foreach($posts as $post)
{{ $post->title }}
@foreach($post->tags as $tag)
{{ $tag->name }}
@endforeach
@endforeach
Saving Data
The way to associate tags with a $post.
It's important to note that creating new tags and associating tags are separate.
Creating a New Tag and Associating Tags
To create a new tag, simply use 'new' and save. Then, attach the created ID to link the tag.
public function tag(Request $request)
{
//When generating a new tag
$tag = new Tag;
$tag->name = $request->name;
$tag->save();
//Creating a new post (you can also find and link an existing post)
$post = new Post;
$post->user_id = 1;
$post->title = 'title';
$post->content = 'content';
$post->save();
//Link the tag (just pass the tag's ID as an argument)
//tags() is the function defined in the Post model
//If you generated a new tag, it would look like this.
$post->tags()->attach($tag->id);
}
Associating Existing Tags with a New Post
public function tag(Request $request)
{
//If not creating a new tag, you can simply request and send the tag ID.
$tag_id = $request->tag_id;
//Creating a new post (you can also find and link an existing post)
$post = new Post;
$post->user_id = 1;
$post->title = 'title';
$post->content = 'content';
$post->save();
//Passing only the ID of an existing tag.
$post->tags()->attach($tag_id);
}
Important Part is,
$post->attach($tag->id);
This part.
If you have already defined the relationship in the model, just this line of code will create data in the intermediate table.
Removing from the Intermediate Table
Similar to 'attach', use 'detach' to simplify the process.
//To remove only one specific tag
$post->detach($tag_id);
//To remove all intermediate tables associated with the post
$post->detach();
That's it.
This article summarizes many-to-many relationships in a way that is easy to understand.
I know the design of the intermediate table might be a bit confusing, but I tried to keep it as concise as possible.
If you have any feedback or find any errors, please contact me via Twitter DM.
Popular Articles
Deploying a PHP7.4 + Laravel6 Project on AWS EC2
Related Articles
How to Save and Display One-to-Many Relations in Laravel【hasMany】
How to Save and Display Many-to-One Relations in Laravel【belongsTo】