So I have this form with 6 input fields. For every submitted empty field I want to insert the value from the previous Database record. How can I do this without writing tons of if-Statements? This is what I tried. It works but once the first condition is true the second one doesn't get executed and its too much code for ALL possible conditions:
if(empty($request->heading)){
$previous_record = HowItWorks::latest('id')->first()->heading;
HowItWorks::create([
'heading' => $previous_record,
'subheading' => $request->subheading,
'caption1' => $request->caption1,
'caption2' => $request->caption2,
'caption3' => $request->caption3,
'caption4' => $request->caption4,
]);
}else if(empty($request->subheading)){
$previous_record = HowItWorks::latest('id')->first()->subheading;
HowItWorks::create([
'heading' => $request->heading,
'subheading' => $previous_record,
'caption1' => $request->caption1,
'caption2' => $request->caption2,
'caption3' => $request->caption3,
'caption4' => $request->caption4,
]);
}
Any help is highly appreciated!!
CodePudding user response:
$previous_record = HowItWorks::latest('id')->first();
HowItWorks::create([
'heading' => $request->heading ?? $previous_record->heading,
'subheading' => $request->subheading ?? $previous_record->subheading,
'caption1' => $request->caption1,
'caption2' => $request->caption2,
'caption3' => $request->caption3,
'caption4' => $request->caption4,
]);