Support the ongoing development of Laravel.io →
Requests Database Eloquent

Hi, i had two modules which are Product and Items Modules Here the relationship between these two module are: Product hasMany items and Items belongsTo product

The table for Product Module are: id, product_name The table for Items Module are: id, products_id, item_name, quantity, price

This is my code for UPDATE

public function update(Request $request)
{
    $product = Product::findOrFail($id);
    $product->product_name = $request->product_name;
    $product->update();
    // Remove all items and add new
    $product->items()->delete();
    // Save each items
    if($request->get('item_name')){
        foreach($request->get('item_name') as $key => $item_name)
        {   
            $items = new Items();
            $items->products_id = $product->id;
            $items->item_name = $item_name;
            $items->quantity = $request->quantity[$key];
            $items->price = $request->price[$key];
            $items->save();
        };
    };
}

The structure for this UPDATE code is whenever there is an update, each items will be deleted and update information will be added as new row.

What i want is the items SHOULD NOT be deleted and add as new. This is because i wants to MAINTAIN THE ITEMS ID. What should i modified to my current code?

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

icodejc icodejc Joined 10 Dec 2016

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.