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];
0

1 Answer 1

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]
Sign up to request clarification or add additional context in comments.

2 Comments

@vimuth use input() method for data, and findOrFail() for exception (in case the id doesnt exist) it will return a 404
@N69S improved the answer significantly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.