简体   繁体   中英

How to update master and detail form in laravel?

I have this code in controller to update the data from database:

public function update(Request $request, $id)
{
    $anodizing = Anodizing::find($id);
    $anodizing->date= $request->date;
    $anodizing->number= $request->number;
    $anodizing->item_total = $request->item_total;
    $anodizing->desc= $request->desc;
    if ($request->hasFile('picture')) {
        $anodizing_image = public_path("uploads/reports/anodizing/{$anodizing->picture}");
        if (File::exists($anodizing_image)) {
            File::delete($anodizing_image);
        };
        $file = $request->file('picture');
        $extension = $file->getClientOriginalExtension();
        $filename = $request->number. '-' . date('YmdHms') . '.' . $extension;
        $file->move('uploads/reports/anodizing', $filename);
        $anodizing->picture= $filename;
    }
    $anodizing->save();

    $id = $anodizing->id;
    foreach ($request->addmore as $key => $value) {
        $anodizingdetail = AnodizingDetail::find($value['id']);
        $anodizingdetail->aluminium_id= $value['name'];
        $anodizingdetail->qty = $value['qty'];
        $anodizingdetail->weight= $value['weight'];
        $anodizingdetail->save();
    }

Basically this update method works perfectly to update or edit existing data, but the problem is, what to do if I want to edit and then insert a new row in the detail form?

I'm aware of updateorCreate method in laravel, is that the right method? How to use that? or I need to use something else?

as you said, instead of AnodizingDetail::find use findOrNew

docs: https://laravel.com/docs/master/eloquent-relationships#the-create-method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM