laravel 8 many to many pivot code example

Example 1: laravel many to many relationship with pivot table

$user = User::find(1); //any user we want to find 
$user->trophies()->attach($idOfTrophy); 
//pass id or array of a Trophy ids 
//suppose admin has selected the trophy from a form and trophy id
// is in $request object, then.
$trophyId = $request->trophy_id;
$user->trophies()->attach($trophyId); //record is created in DB.
attach and syncWithoutDetaching both does same job

Example 2: laravel many to many relationship with pivot table

$trophyIds  = Trophy::where('some_column','some_value')                    ->pluck('id')->toArray(); //it will give array of ids.$user->trophies()->detach($trophyIds); //deletes given trophies of $user

Tags:

Php Example