This is the correct way to handle this situation. But ideally, you would rename the form fields so that they are valid php variables and match your db schema
Form Input Element Names Different to Table Column Names
I have a MySQL table that includes column names containing underscores: legal_name and trading_name. I have an update form whose corresponding input elements have name attributes, using hyphens, of legal-name and trading-name respectively.
This is my original update() method in the controller:
public function update(Request $request, string $id) {
$bank = Bank::find($id);
$bank->update($request->all());
return redirect()->route('banks.index');
}
No records were being updated as I guess Eloquent assumes that table column names are the same as the name attributes for form elements.
So, I changed the controller's update() method:
public function update(Request $request, string $id) {
$bank = Bank::find($id);
$bank->update([
'legal_name' => $request->{'legal-name'},
'trading_name' => $request->{'trading-name'}
]);
return redirect()->route('banks.index');
}
This works, but after a lot of searching I was unable to confirm that this is the correct way. In fact the majority of search results mention using accessors and mutators, but I can't quite see how they fit.
Would be grateful for some guidance on this.
Many thanks, Steve.
Please or to participate in this conversation.