Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Alex Fts's avatar

How to update recode in many to many relation Laravel

Business Model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Business extends Model
{
    use HasFactory;

 /**
         * The roles that belong to the Business
         *
         * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
         */
        public function cat()
        {
            return $this->belongsToMany(BusinessCategory::class, 'cat_business',  'business_id' , 'cat_id');
        }

}

Business Category Model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\Business;

class BusinessCategory extends Model
{

    use HasFactory;
    protected $guarded = [];

    public function business()
    {
        return $this->belongsToMany(Business::class, 'cat_business','business_id', 'cat_id' );
    }
}

Trying to use updateexistingpivot

 $business = Business::find($id);
  $business->cat()->updateExistingPivot($request->cat_id );

Error


Too few arguments to function Illuminate\Database\Eloquent\Relations\BelongsToMany::updateExistingPivot(), 1 passed in D:\xampp\htdocs\finallisting\app\Http\Controllers\BusinessController.php on line 194 and at least 2 expected

What Would be Second Parameter of Povit relation

      $business->cat()->updateExistingPivot($request->cat_id , [Second Perameter??] );
0 likes
5 replies
tykus's avatar

You're using it wrong. What is the extra pivot column here?

It looks like you really need either sync or attach here

Alex Fts's avatar

@tykus I am using attach for inserting can i also use it for update

 $business->cat()->attach($request->cat_id);
tykus's avatar

@Alex Fts you can use attach any time you want. I don't know what your business logic is however; what are you actually wanting to achieve - to ensure $request->cat_id is associated with the Business? Use syncWithoutDetaching in that case; because attach will make a new association even if another is existing.

Alex Fts's avatar

@tykus I just want to show multiple categories against a single business and in update crud i want to update the selected categories against the business

While I am using syncWithoutDetaching it can add a new category in business but can't remove the old one

tykus's avatar
tykus
Best Answer
Level 104

@Alex Fts again, as I mentioned earlier I do not know your business logic!

it can add a new category in business but can't remove the old one

Use sync in that case

1 like

Please or to participate in this conversation.