Laravel – `syncWithoutDetaching()` vs `insertOrIgnore()`

  • Post category:Snippets

In a tweet by Tom Herrmann (@devgummibeer) (https://gummibeer.dev/), he discussed how using syncWithoutDetaching() call can kill a database.

Basically, instead of doing:

$user->identifiers()->syncWithoutDetaching($identifiers);

Do this:

DB::table('identifier_user')->having()->insertOrIgnore(
  $identifiers->map(fn (Identifier $identifier) => [
    'identifier_id' => $identifier->getKey(),
    'user_id' => $user->getKey(),
  ])->all()
);

This resulted in an 80% drop in CPU usage and the average job runtime also dropped from ~2-4s to ~0.2s.

Combining with a delete action, this could also be used to replace sync().

Full details can be found in the Twitter Thread.