xxxxxxxxxx
$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
xxxxxxxxxx
$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
xxxxxxxxxx
// how to make many to many relationship in multiple database connection
//User model (default database connection)
// Role model (database connection 2)
// RoleUser model (database connection 2)
// when you need to make users many to many relationshps with roles from another connection,
// you must put role_user pivot table in another connection,
// if not, it will get this error 'invali_object_name role_user'
class User extends Model
{
public function roles(): BelongsToMany
{
return $this->belongsToMany(Role::class, 'role_user');
}
}