update Controller

Posted 1 month ago by Aqeel94321

I have issue related to one to many relation in update method.In update i want to check value from database. if value have then update it otherwise create new one. here is my code

$companyinfo =CompanyInfo::find($id) ;
        if ($request->file('image')){
            File::delete($companyinfo->image);
            $imageName = time().'.'.request()->image->getClientOriginalExtension();
            request()->image->move(public_path('slider/image'), $imageName);
            $companyinfo->image = 'companylogo/image/'.$imageName;
        }

        $companyinfo->name = $request->name;
        $companyinfo->description = $request->description;
        $companyinfo->save();

        $count=count($request->address);
        if ($request->address && $request->city && $request->state && $request->zipcode && $request->phone) {
            for( $i=0; $i<$count;$i++) {
                $masterList = $companyinfo->locate()->where('company_info_id',$request->id)->first();
                if($masterList!=null){
                    $companyinfo->locate()->where('company_info_id', $request->id)->update([
                        'company_info_id' => $companyinfo->id,
                        'address' => $request->address[$i],
                        'city' => $request->city[$i],
                        'state' => $request->state[$i],
                        'zipcode' => $request->zipcode[$i],
                        'phone' => $request->phone[$i],
                    ]);
                }
                else{
                    $companyinfo->locate()->create([
                        'company_info_id' => $companyinfo->id,
                        'address' => $request->address[$i],
                        'city' => $request->city[$i],
                        'state' => $request->state[$i],
                        'zipcode' => $request->zipcode[$i],
                        'phone' => $request->phone[$i],
                    ]);
                }

            }
        }

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.