Home > Net >  using different name of html input than the DB column name in Laravel
using different name of html input than the DB column name in Laravel

Time:06-19

how can i use a name for html input that is differ from the column name that i want to save this input data to

i usually use this method since all html inputs names are equal to DB columns :

Model::create($request->all());

Now i know i can use this:

Model::create([
'name' => $request->name,
'feild' = > $request=>value,
etc.
]);

but i have a lot of values and i don't want to rewrite it over and over , so is there a way that combine the $request->all() with the second method ?

CodePudding user response:

One way to do it is to use https://laravel.com/docs/9.x/collections#method-merge merge() to add fields, and use https://laravel.com/docs/9.x/collections#method-only to return only the fields you want to add to your model, or https://laravel.com/docs/9.x/collections#method-except except() for the inverse

$request->merge([
  'new_column_name' => $the_value_you_want_to_use,
  'old_column_name' => the_value_you_donot_want
]);
$request->only('new_column_name')

// or

$request->except('old_column_name')
  • Related