good afternoon,
I am running into an issue, which I can't solve myself. I have an application where I have form with flexible fields. If I create these then it all works fine. Using livewire I can add and remove fields. I already made great progress thanks to MichalOravec as well. But I proceed and in the end, i failed to proceed myself.
Now I run into the following, if I want to edit a field, then I can only edit the existing fields. If I add a field, then only the already existing fields are saved. Which makes sense given the code below. I have already looked if I could solve it with the fill() method but that did not work. Also workarounds with array_diffs or nested foreach, etc did not solve it.
So my question is, how can I make sure that the extra field is saved?
As a starter my ddd(), purely to show what the fields are
I have 3 fields, but only Field1 and Field 2 are being saved. (Exists already in de database, corresponding the ID) But field 3 is not saved. Again which makes sense because of my code, but How can I solve this one?
array:7 [▼
"_token" => "BmSdIF1Xldth6G8IvJnjfs0JkDnbM4ZR9owLyQ4l"
"_method" => "PUT"
"id" => "1"
"name" => "Git Push"
"description" => "Voor Git"
"flow_id" => "1"
"field" => array:3 [▼
1 => "Field 1"
16 => "Field 2"
17 => "Field 3"
]
]
```
Controller:
```
public function update(Request $request, $id)
{
$command = Command::findOrFail($id);
$command->id = $request->id;
$command->name = $request->name;
$command->description = $request->description;
$command->flow_id = $request->flow_id;
foreach ($request->field as $id => $value) {
$test = $command->fields()->where('id', $id)->update(['field' => $value]);
}
$command->save();
return redirect('/admin/commands')->with('success', 'Command is successfully updated');
}
Form
<input type="text" name="field[]"
class="px-4 py-2 border focus:ring-gray-500 focus:border-gray-900 w-full sm:text-sm border-gray-300
rounded-md focus:outline-none text-gray-600"
placeholder="Field {{('Describe ' .$field)}}"> </div>
Command model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Command extends Model
{
use HasFactory;
protected $fillable = ['name', 'description', 'flow_id'];
public function flow()
{
return $this->belongsTo(Flow::class);
}
public function fields()
{
return $this->hasMany(Fields::class);
}
}
I hope someone can point me into the right direction.
Kr