[Osaka/Yokohama/Tokushima] Looking for infrastructure/server side engineers!

[Osaka/Yokohama/Tokushima] Looking for infrastructure/server side engineers!

[Deployed by over 500 companies] AWS construction, operation, maintenance, and monitoring services

[Deployed by over 500 companies] AWS construction, operation, maintenance, and monitoring services

[Successor to CentOS] AlmaLinux OS server construction/migration service

[Successor to CentOS] AlmaLinux OS server construction/migration service

[For WordPress only] Cloud server “Web Speed”

[For WordPress only] Cloud server “Web Speed”

[Cheap] Website security automatic diagnosis “Quick Scanner”

[Cheap] Website security automatic diagnosis “Quick Scanner”

[Reservation system development] EDISONE customization development service

[Reservation system development] EDISONE customization development service

[Registration of 100 URLs is 0 yen] Website monitoring service “Appmill”

[Registration of 100 URLs is 0 yen] Website monitoring service “Appmill”

[Compatible with over 200 countries] Global eSIM “Beyond SIM”

[Compatible with over 200 countries] Global eSIM “Beyond SIM”

[If you are traveling, business trip, or stationed in China] Chinese SIM service “Choco SIM”

[If you are traveling, business trip, or stationed in China] Chinese SIM service “Choco SIM”

[Global exclusive service] Beyond's MSP in North America and China

[Global exclusive service] Beyond's MSP in North America and China

[YouTube] Beyond official channel “Biyomaru Channel”

[YouTube] Beyond official channel “Biyomaru Channel”

I want to use intermediate tables in Laravel! How to use the sync method

thank you for your hard work!
My name is Yamada from the System Development Department.

This time, I will explain the sync method used when using intermediate tables in Laravel.

What is the sync method?

If the table relationship is many-to-many, I think the solution is basically to use an intermediate table.
At that time, it is an excellent tool that allows you to easily perform operations such as registering, updating, and deleting data in the intermediate table by using the sync method.
Let's take a look at some concrete examples.

Preparation (table configuration)

When using the sync method, assume the following situation.

  • I want to link users and hobbies and add comments to the relationship.
  • One user can have multiple hobbies
  • One hobby can be selected by multiple users.

The table configuration to achieve the above is assumed as follows.

  • users table that holds the names of users
id name
1 taro
2 hanako
3 saburo
  • Hobbies table to hold names of hobbies
id name
1 movie
2 youtube
3 study
  • Intermediate table (hobby_user table) that represents the relationship between users and hobbies and can add comments
id user_id hobby_id comment
1 1 1 I quite like it
2 1 2 I quite like it
3 2 1 I quite like it

We will proceed with the following discussion assuming that we have prepared a migration file in Laravel with the above contents, and inserted the data described in the users and hobbies tables.

Preparation (Laravel model file)

Write the following to represent a many-to-many relationship in the Laravel model file.

// hobby model public function users() { return $this->belongsToMany(User::class); } // users model public function hobbies() { return $this->belongsToMany(Hobby::class); }

Now that we are ready to use the sync method, we will use it from now on.

sync method

First of all, I would like to register the data.
If you want to add movies (hobby_id:1) to taro's (user_id:1) hobbies, you can express it as follows.

$user = User::find(1); $user->hobbies()->sync(1);

If you want to make comments or multiple registrations at once, you can express it as follows.
It is assumed that taro (user_id:1) will add youtube (hobby_id:2) and study (hobby_id:3) to his hobbies, and will also include comments.

$user = User::find(1); $user->hobbies()->sync([ 2 => ['comment' => 'I like it a lot'], 3 => ['comment' => 'I like it a lot' '], ]);

However, there is a caveat here.

is the DB when this code is executed on the DB with movies (hobby_id:1) added to taro's (user_id:1) hobbies

The data that added movies (hobby_id:1) to taro's (user_id:1) hobby has disappeared.
This is because the sync method, as the name suggests, is a method that synchronizes the specified data state.
*sync: Synchronization

By taking advantage of this synchronized nature, data can be easily deleted and updated.
Consider changing taro(id:1)'s hobby to the following.
youtube(hobby_id:2), study(hobby_id:3)⇒movie(hobby_id:1), youtube(hobby_id:2)

The current DB is as follows.

If you run this code below

$user = User::find(1); $user->hobbies()->sync([1,2]);

The result is below.

Normally, I would have deleted study (hobby_id:3) and then added movie (hobby_id:1), but by using the sync method I was able to do it in one go.
Also, the part you should know about the behavior is the id=2 part.
Comments are not specified this time, but they remain as they are.
This is because what is synchronized is only the relationship between the specified user_id and hobby_id, and hobby_id=2 does not need to be changed, so the record remains as is without being updated or deleted.

Application of sync method

We explained that the sync method is a method that synchronizes, but it is actually possible to just register without synchronizing.
The way to do that is to declare false as the second argument.
Continuing from the previous table, let's add study (hobby_id:3) to taro's (id:1) hobby.

$user = User::find(1); $user->hobbies()->sync(3, false);

By specifying false for the second argument, the movie (hobby_id:1) and youtube (hobby_id:2) that originally existed were not deleted, and the study (hobby_id:3) was successfully added.
However, setting false is an action that is easy to forget, and if you do not specify it, there is a risk of unintentionally erasing data.
Therefore, specifying the syncWithoutDetaching method instead of specifying false will have the same effect.

$user = User::find(1); $user->hobbies()->syncWithoutDetaching(3);

summary

This time, we introduced the sync method, which is useful when registering, changing, and deleting intermediate tables in Laravel.
I think this method is very easy to use once you understand the nature of synchronization.
Also, the syncWithoutDetaching method introduced at the end only executes the sync method with false specified internally in Laravel, but
by having such a method, you can prevent accidental mistakes. It's a very easy to use method.

Let's all master the sync method and enjoy coding every day!
Well then! !

lastly

I have opened the system development service site "SEKARAKU Lab" to which I belong.
Beyond is a one-stop service for everything from server design and construction to operation, so if you have any trouble with server-side development, please feel free to contact us.
SEKARAKU Lab: https://sekarakulab.beyondjapan.com/

If you found this article helpful , please give it a like!
5
Loading...
5 votes, average: 1.00 / 15
12,248
X facebook Hatena Bookmark pocket
[2025.6.30 Amazon Linux 2 support ended] Amazon Linux server migration solution

[2025.6.30 Amazon Linux 2 support ended] Amazon Linux server migration solution

The person who wrote this article

About the author

Yuki Yamada

Joined Beyond Co., Ltd. in 2021
My hobbies are karaoke and board
games.My board games can no longer fit on one shelf, so I would like to buy a new shelf, but I am sad because I don't have a place to put a shelf at home.
He has experience in mold design and sales, and has gained a wide variety of experience and has settled into a job as a server-side engineer.
He is currently working on server-side development using PHP and Python.
He also wants to learn a front-end language in the future, and is interested in Next.js, a React-based front-end framework.