Shady Atef Shady Atef - 23 days ago 7
PHP Question

is there Any Way to edit Many To Many Relation Ship without attaching-detaching in Laravel

After spending hours and following the code, I found that Laravel has no way of Editing The Intermediate table in Many To Many Relation without detaching and attaching ..
This is okay but it has a big disadvantage.
Applying the app on big scale, the

id
index increases rapidly.
So I wonder if there are anyway ? And how to overcome this ID problems
(I though about cron jobs to reindex it)

Answer

Of course there is! Suppose you have this database structure, where User and Group share a many-to-many relationship, with a valid field in the pivot (intermediary) table.

+-------------+  +-------------+  +-------------+
| users       |  | groups      |  | group_user  |
+-------------+  +-------------+  +-------------+
| id          |  | id          |  | group_id    |
| name        |  | name        |  | user_id     |
| email       |  | desc        |  | valid       |
+-------------+  +-------------+  +-------------+

Now, since the valid column is not strictly necessary for the relationship, you'll have to tell Laravel to specifically fetch this row. For the sake of simplicity, I'll call it right in the example, but if you need it very often, you'd probably want to put that in the model relationship itself, on User.groups and Group.users methods.

// Retrive the user with ID one
$user = User::find(1);

// This tells Laravel to fetch the `valid` column, when
// the user's groups
$userGroups = $user->groups()->withPivot('valid')->get();

// Get the first group
$firstGroup  = $userGroups->first();

// Change the `valid` value for that first group
$firstGroup->pivot->valid = true;

// Save the changes
$firstGroup->pivot->save();
Comments