Skip to content

Instantly share code, notes, and snippets.

@nnivxix
Last active August 12, 2023 04:45
Show Gist options
  • Select an option

  • Save nnivxix/b38b0b46dcd48c769efd652b8e187c80 to your computer and use it in GitHub Desktop.

Select an option

Save nnivxix/b38b0b46dcd48c769efd652b8e187c80 to your computer and use it in GitHub Desktop.
Attach, detach and sync many-to-many relationships in Laravel

Attach, detach and sync many-to-many relationships in Laravel

1.attach is insert value to pivot table relation

when we run this code $user->roles()->attach([3]); that will be add/insert data to table user_role

role_id user_id
3 1

2.sync is add value and delete to pivot table relation

If user_role table have

role_id user_id
1 1
2 1
// run this syntax
$user->roles()->sync([3, 2])
role_id user_id
2 1
3 1

3. detach is remove value in pivot table relation

If we have data like this

role_id user_id
2 1
3 1
1 1

when we try to run this code $user->roles()->detach(); that will be remove all data, but if we add the arguments on function detach $user->roles()->detach(1); will remove only role_id : 1

role_id user_id

4. syncWithoutDetaching is add value without detach and duplicate when run twice

Let say we have table with value like this

role_id user_id
3 1

when we insert using code syncWithoutDetaching example $user->roles()->syncWithoutDetaching([1, 2]); will be insert value role_id 1 and 2

role_id user_id
3 1
1 1
2 1
<?php
namespace App\Console\Commands;
use App\Models\User;
use Illuminate\Console\Command;
class TestRelation extends Command
{
protected $signature = 'rel:db';
protected $description = 'Command description';
public function handle()
{
// $this->attach();
$this->sync();
// $this->detach();
// $this->syncWithoutDetaching();
}
public function attach()
{
$user = User::find(1);
$user->roles()->attach([ 2, 3]);
}
public function sync()
{
$user = User::find(1);
$user->roles()->sync([3, 2]);
}
public function detach()
{
$user = User::find(1);
$user->roles()->detach();
}
public function syncWithoutDetaching()
{
$user = User::find(1);
$user->roles()->syncWithoutDetaching([1, 2, 3]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment