Home  >  Q&A  >  body text

Using different html input name than database column name in Laravel

How to use a different html input name than the column name I want to save this input data to

I usually use this method because all html input names are equal to the database 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 again, so is there a way to combine $request->all() with the second method?

P粉818125805P粉818125805300 days ago366

reply all(2)I'll reply

  • P粉627027031

    P粉6270270312024-01-17 11:55:32

    I found that the PHP array_merge() function can be used as follows:

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

    reply
    0
  • P粉731977554

    P粉7319775542024-01-17 09:29:07

    One way is to add the fields using https://laravel.com /docs/9.x/collections#method-merge merge() and use https://laravel. com/docs/9.x/collections#method-only Return only fields to be added to the model, or https://laravel.com/docs/9.x/collections#method-except except() 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')
    

    reply
    0
  • Cancelreply