1

I need to update HasMany relation with set of id's.

Faq model.

class Faq extends Model
{
   public function products(){
        return $this->belongsToMany(Product::class, 'faq_products');
   }
}

I have Product model and pivot table 'faq_products' for HasMany relation.

faq_products table

    Schema::create('faq_products', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->bigInteger('faq_id')->unsigned()->nullable();
        $table->foreign('faq_id')->references('id')->on('faqs')->onDelete('cascade');
        $table->integer('product_id')->unsigned()->nullable();
        $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
        $table->timestamps();
    });

And I'm getting an array of product ids from request related to faq but not sure how to update the relationship.

array

$product_ids = [4, 3, 2];
shaedrich
  • 5,457
  • 3
  • 26
  • 42
vimuth
  • 5,064
  • 33
  • 79
  • 116

1 Answers1

2

I bet, it's attach() you're looking for:

class FaqController extends Controller
{
    public function update(Request $request)
    {
        $faq = Faq::findOrFail($request->input('faq_id');
        //attached products [4,5,6]
        $faq->products()->attach($request->input('product_ids')); // [4, 3, 2];
        //attached products [2,3,4,5,6]
    }
}

If you have previously attached other products (example id = 4, 5 and 6) and you want to remove them while attaching 4, 3 and 2; use sync() instead of attach

//attached products [4,5,6]
$faq->products()->sync($request->input('product_ids')); // product_ids = [4,3,2]
//attached products [4,3,2]
shaedrich
  • 5,457
  • 3
  • 26
  • 42