I have a dynamic form where the user should be able to add or remove fields while editing.
I am able to update the exact number fields that are in the database table. But what I want is if a user clicked a 'Delete Subject'
and 'Update'
buttons, I want that entire row deleted from the database.
And, if he added a subject by clicking 'Add another Subject'
the form and clicked 'Update'
I want those subjects added. What am I missing here?
Note: I built a One-to-Many relation between New and Subjects, where a New has many subjects and many subjects belong to a New (It works fine).
My form looks like this
New Model
protected $fillable = ['name', 'address'];
public function subjects() {
return $this->hasMany(Subjects::class, 'new_id');
}
Subjects Model
protected $fillable = ['new_id', 'sub_code', 'sub_name', 'sub_img'];
public function subs(){
return $this->belongsTo(New::class, 'new_id');
}
Create Method
public function create(Request $request, New $new){
$new = New::FindorFail($id)
$subjects= [];
$sub_images = $request->file('sub_img');
$sub_name = $request->sub_name;
for ($i=0; $i < count(request('sub_code')); ++$i)
{
$subjects = new Subjects;
$subjecs->sub_code = request('sub_code')[$i];
$subjects->sub_name = request('sub_name')[$i];
$sub_img_name = uniqid() . '.' . $sub_images[$i]->getClientOriginalExtension();
$sub_images[$i]->move(public_path('/images/'), $sub_img_name);
$subjects->sub_img = '/images/'.$sub_img_name;
$new->subjects()->save($subjects);
}
}
Update Method
public function update(Request $request, $id){
$new=New::FindOrFail($id)
$subjects = Subjects::with(['subs'])->where('new_id', $new->id)->get();
$new->update($request->all());
$i=0;
foreach( $subjects as $new_subjects)
{
$sub_images =request()->file('sub_img');
$sub_name = request('sub_name');
if(isset($sub_images[$i]))
{
$pathToStore = public_path('images');
if($request->hasFile('sub_img') && isset($sub_images[$i]))
{
$sub_img_name = uniqid() . '.' . $sub_images[$i]->getClientOriginalExtension();
$sub_images[$i]->move(public_path('/images/'), $sub_img_name);
$new_subjects->sub_img = '/images/'.$sub_img_name;
$new_subjects->sub_code = request('sub_code')[$i];
$new_subjects->sub_name = request('sub_name')[$i];
$new_subjects->sub_img = "images/{$sub_img_name}";
$i++;
$new->subjects()->save($new_subjects);
}
}
}
}
Subjects Database
I want this table row be updated (added or deleted) after user edit the form.