Update dynamic form fields in database (Insert/Delete)

Posted 8 months ago by lara_net

I have a dynamic form where the user should be able to add or remove data while updating.

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?

My Edit View

<form accept-charset="UTF-8" action="{{action('[email protected]', $id)}}" enctype="multipart/form-data" method="post" files="true">
<label>Student Name:</label> <input type="text"  name="name">
<label>Student Address:</label> <input type="text" name="name">
<label>Student Subject Feature</label>

@foreach($subjects as $sub)
<input type="text" name="sub_code[]" value="{{ $sub->sub_code  }}" placeholder="Subject Code">
<input type="text" name="sub_name[]" value="{{ $sub->sub_name  }}" placeholder="Subject Name">
<input type="file" name="sub_img[]">
<a href="#" class="remove_field">Delete This Subject</a>
<button class="add_more">Add Subject</button>

<button type="submit">Update</button>

My form Subject Screenshot

Students Model

protected $fillable = ['name', 'address'];
public function subjects() {
    return $this->hasMany(Subjects::class, 'stu_id');

Subjects Model

protected $fillable = ['stu_id', 'sub_code', 'sub_name', 'sub_img'];

public function subs(){
    return $this->belongsTo(Students::class, 'stu_id');

Update Method

public function update(Request $request, $id){
$subjects = Subjects::with(['subs'])->where('stu_id', $stu->id)->get();

foreach( $subjects as $new_subjects)
    $sub_images =request()->file('sub_img');    
    $sub_name = request('sub_name');
       $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}";

Subjects Database

Subject Database

What am I missing? Should I use other method for UpSert?

Please sign in or create an account to participate in this conversation.

Laracasts Mascot

Hi, Have We Met Yet?

Did you know that, in addition to the forum, Laracasts includes well over 1000 lessons on modern web development? All for the price of one lunch out per month.

Sign Me Up


Reply to

Use Markdown with GitHub-flavored code blocks.