Update dynamic form fields in database (Insert/Delete)

Published 6 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>
@endforeach
<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){
$stu=Students::FindOrFail($id)
$subjects = Subjects::with(['subs'])->where('stu_id', $stu->id)->get();
$stu->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

Subject Database

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

biishmar

@lara_net

So your question is whenever u click add another subject and update, u r not getting those data to back end?

lara_net

Ya, I'm not getting the updated number of rows in the database. However, I can update the exact number of rows that are saved in database. ie.

If I add one subject if there are 2 subjects already, that new row is not added.

biishmar

@lara_net

So this is front end problem..

  • R u using form submit or ajax call?
  • if its form submit, add button appending new row inside form tag?
  • please provide your html and javascript coding for further checking.
lara_net

I use HTML submit button to update. From Laravel Update method, I want to update the data. (Question updated.)

Dry7
Dry7
6 months ago (152,030 XP)

@lara_net try this code, I did not test it, but the meaning is correct and add jquery.

<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)
<div class="sub">
<input type="text" name="sub_code[{{ $sub->id }}]" value="{{ $sub->sub_code }}" placeholder="Subject Code">
<input type="text" name="sub_name[{{ $sub->id }}]" value="{{ $sub->sub_name }}" placeholder="Subject Name">
<input type="file" name="sub_img[{{ $sub->id }}]">
<a href="javascript:deleteSub(this, {{ $sub->id }});" class="remove_field">Delete This Subject</a>
</div>
@endforeach
<button class="add_more">Add Subject</button>

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

<script type="text/javascript">
function addSub()
{
    $('.add_more').prepend('<div class="sub">
<input type="text" name="new_sub_code[]" placeholder="Subject Code">
<input type="text" name="new_sub_name[]" placeholder="Subject Name">
<input type="file" name="new_sub_img[]">
<a href="javascript:deleteSub(this, 0);" class="remove_field">Delete This Subject</a>
</div>');
}

function deleteSub(el, id)
{
    if (Number(id) > 0) {
        $(el).parents('form').append('<input type="hidden" name="delete_sub[]" value="' + id + '" />');
    }
    $(el).parent().remove();
}
</script>
public function update(Request $request, $id){
  $stu=Students::FindOrFail($id)
  $subjects = Subjects::with(['subs'])->where('stu_id', $stu->id)->get();
  $stu->update($request->all());

  /** Old subjects */
  $sub_images = request()->file('sub_img');    
  $sub_names  = request('sub_name');
  foreach (request('sub_code') as $id => $code) {
    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); 
           
           $sub = Subject::find($id);
           $sub->sub_code = $code;
           $sub->sub_name = $sub_names[$i];
           $sub->sub_img = "images/{$sub_img_name}";
           $sub->save();
           
      }
    }
  }

  /** New subjects */
  $sub_images = request()->file('new_sub_img');    
  $sub_names  = request('new_sub_name');
  $sub_codes  = request('new_sub_code');
  foreach ($sub_codes as $i => $code) {
    if(isset($sub_images[$i])) {
       $pathToStore = public_path('images');    
       if($request->hasFile('new_sub_img') && isset($sub_images[$i])) {
          $sub_img_name = uniqid() . '.' . $sub_images[$i]->getClientOriginalExtension();
           $sub_images[$i]->move(public_path('/images/'), $sub_img_name); 
           
           $sub = new Subject([
               'sub_code' => $code,
               'sub_name' => $sub_names[$i],
               'sub_img' => "images/{$sub_img_name}",
           ]);
           $sub->save();
           
      }
    }
  }

  /** Delete subjects */
  foreach (request('delete_sub') as $id) {
    Subject::find($id)->delete();
  }
}
lara_net

I use [Bootstrap/jQuery Image uploader plugin] (https://github.com/egonolieux/bootstrap-imageupload).

lara_net

Is shows

ErrorException Invalid argument supplied for foreach()

Are there any Events in Laravel, that I can be tracked and fire once the user clicked 'Update' button?

Dry7
Dry7
6 months ago (152,030 XP)

@lara_net

foreach ((array)request('sub_code') {}
foreach ((array)$sub_codes as $i => $code) {}

Are there any Events in Laravel, that I can be tracked and fire once the user clicked 'Update' button?

https://laravel.com/docs/5.5/broadcasting

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