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

Cvetan's avatar

Best practice for CRUD process to manage many to many relations such as product-categories

What would basic process look like?

I would have some checkbox list with categories id. I would select those. How would i then save those relations, and update(if needed) on update operation?

Is there some common practice that doesn't involve disecting input manually and separating categories from array input(categories[])?

0 likes
6 replies
martinbean's avatar

@Cvetan Using resourceful controllers, you might have a ProductCategoryController, with an update method that looks like this:

class ProductCategoryController extends Controller
{
    public function update(Request $requst, Product $product)
    {
        $product->categories()->sync($request->input('category'));
    }
}

The route might look like this:

Route::put('products/{product}/categories', 'ProductCategoryController@update');

Submit a category[] array to this URI, and it’ll sync the given category IDs on the product.

Cvetan's avatar

Yeah, but that will not be separate from product update.

It needs to happen on product update. Othervise i would select product categories on separate form? If i understood you right?

martinbean's avatar
Level 80

@Cvetan You can use the same code when updating a product:

class ProductController extends Controller
{
    public function update(UpdateProductRequest $request, Product $product)
    {
        $product->update($request->all());

        $product->categories()->sync($request->input('category'));

        // Redirect back to edit form or something
    }
}
Cvetan's avatar

@martinbean So i don't need to ignore that in product data? I thought if i use $request->all() for product i need somehow ignore categories input.

martinbean's avatar

@Cvetan So long as your properties are properly fillable, it’ll just disregard any input data that doesn’t match a fillable property.

Please or to participate in this conversation.