简体   繁体   中英

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

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 ?

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')

我发现可以使用 PHP array_merge() 函数,如下所示:

Model::create(array_merge($request->all(),['DB fieldName' => $newValue]));

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