in my laravel app I have a many to many relationhip between user and badges, where an user can only select a badge of a given category (can't have more than one badge of the same category).
Users will select one badge of each given badge category from a selectable.
So what I want to do is check if there is a badge relationship belonging to the selected category, if there is not then I attach the id, if already one exists, I detach current one and then attach new one.
Migrations:
public function users()
{
return $this->belongsToMany('App\Models\User', 'user_badge', 'badge_id', 'user_id');
}
public function badges()
{
return $this->belongsToMany('App\Models\Badge', 'user_badge', 'user_id', 'badge_id');
}
Schema::create('badges', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('badgecategory_id')->index();
$table->foreign('badgecategory_id')->references('id')->on('badgecategories')->onDelete('cascade')->onUpdate('cascade');
$table->string('title');
$table->string('icon')->nullable();
$table->timestamps();
});
Schema::create('user_badge', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id')->index()->nullable();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
$table->unsignedInteger('badge_id')->nullable()->index();
$table->foreign('badge_id')->references('id')->on('badges')->onDelete('cascade')->onUpdate('cascade');
$table->timestamps();
});
Now some pseudo code
$hasBadgeId = $badge = where badge category is givenCategoryId
if($hasBadgeId)
{
$user->badges()->dettach($hasBadgeId);
$user->badges()->attach($badgeId);
}
else
{
$user->badges()->attach($badgeId);
}