Laravel Update Many-to-Many Foreign Key Record

Active3 hr before
Viewed126 times

7 Answers


You can try updateExistingPivot(), Oh, you've updated your question with updateExistingPivot(). I wonder what is $userRoleId in your example? It's an old role ID? – Alexey Mezenin Nov 13 '16 at 9:41 ,If you're using more than one pair of exactly the same user_id and role_id and you want to update only one row, try to use newPivotStatement():, What happens if you touch a piece that cannot move?

$user - > roles() - > updateExistingPivot($roleId, ['role_id' => $newRoleId]);
load more v

Using the loadCount method, you may load a relationship count after the parent model has already been retrieved:,Eloquent determines the foreign key of the relationship based on the parent model name. In this case, the Phone model is automatically assumed to have a user_id foreign key. If you wish to override this convention, you may pass a second argument to the hasOne method:,However, if the foreign key for your relationship does not follow these conventions, you may pass a custom foreign key name as the second argument to the belongsTo method:,However, you may find it more convenient to use the whereBelongsTo method, which will automatically determine the proper relationship and foreign key for the given model:

Eloquent relationships are defined as methods on your Eloquent model classes. Since relationships also serve as powerful query builders, defining relationships as methods provides powerful method chaining and querying capabilities. For example, we may chain additional query constraints on this posts relationship:

$user - > posts() - > where('active', 1) - > get();
load more v

$user - > roles() - > sync([1, 2, 3]);
load more v

So in this tutorial, you can understand how to create many-to-many relationships with migration with a foreign key schema for one to many relationships, use sync with a pivot table, create records, attach records, get all records, delete, update, where condition and everything related to many to many relationship.,I hope you understand of many to many relationship...,In this example, i will create "users", "roles" and "role_user" tables. each table is connected with each other. now we will create many to many relationships with each other by using the laravel Eloquent Model. We will first create database migration, then model, retrieve records and then how to create records too. So you can also see database table structure on below screen.,Now we have to create migration of "users", "roles" and "role_user" table. we will also add foreign key with users and roles table. so let's create like as below:

Schema::create('users', function(Blueprint $table) {
   $table - > increments('id');
   $table - > string('name');
   $table - > string('email') - > unique();
   $table - > string('password');
   $table - > rememberToken();
   $table - > timestamps();
load more v

The database tables are now set up, but you still need to configure the Eloquent models to define the relationship between them.,To get started, you’ll need to create a model and a database table to represent a List of links. Then, you’ll update the existing Link model and table to include the relationship between both models. Because the term List is reserved for PHP internals, you won’t be able to name your new model with that term. You can call this new model LinkList instead.,Next, include the following line in the table definition, within the up method and right after the line that sets up the description field:,This approach to handling data-only with Eloquent means that you don’t need to set up any properties for the LinkList class because they will be inferred from the database table structure for that model.

First, make sure you’re in the application directory:

load more v

In order to add new relation use attach or sync.,1 attach will add new row on the pivot table without checking if it's already there. It's good when you have additional data linked to that relation, for example:,Difference between the two is:,or it will setup new relations without detaching previous AND without adding duplicates:

Can anyone help me on how to save many to many relationship? I have tasks, user can have many tasks and task can have many users (many to many), What I want to achieve is that in update form admin can assign multiple users to specific task. This is done through html multiple select input

name = "taskParticipants[]"

This is my User model:

function tasks() {
   return $this - > belongsToMany('Task', 'user_tasks');

Task model

function taskParticipants() {
   return $this - > belongsToMany('User', 'user_tasks');


function update($task_id) {
   if (Input::has('taskParticipants')) {
      foreach(Input::get('taskParticipants') as $worker) {
         $task2 = $task - > taskParticipants - > toArray();
         $task2 = array_add($task2, $task_id, $worker);
         $task - > taskParticipants() - > sync(array($task2));

This is structure of tables tasks id|title|deadline

id | task_id | user_id
load more v

And yes, for the umpteenth time, I’m aware that this invoices table has a lot missing; however, our focus here is to see how model relationships work and not to design an entire database.,We only have a couple more models to worry about. The first one is the invoices table, and you’ll remember that we decided to make it a one-to-one relationship with orders.,As you can see, we add a separate column here, called category_id, which will store IDs from the categories table. No prizes for guessing, this creates a one to many relationships at the database level.,In other words, we need to first create the migrations (and model files) for all the models, which will be applied to the database. Later, we can work on the models and tack on the relationships.

For this example (users and accounts), this is how we can implement this relationship when creating the schema:

   email VARCHAR(100) NOT NULL,
   password VARCHAR(100) NOT NULL,

CREATE TABLE accounts(
   role VARCHAR(50) NOT NULL,
load more v

Other "update-undefined" queries related to "Laravel Update Many-to-Many Foreign Key Record"