Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Danny971's avatar

Database table wont be updated

I am trying create a feature to update the tables based on what the user wants . example if the user makes a mistake they could edit the records

here is my code

Controller - SaveProfileEditsController.php



 public function SavefamdemoEdits(Request $req, $id){

         $profilefamilydemographics = FamilyDemographicsModel::find($id);

         if($profilefamilydemographics) {

            $identifier = $req->input('identifier');

            $firstnameCorrection  = $req -> input('name');
            $lastnameCorrection  = $req -> input('surname');
            $ageCorrection  = $req -> input('age');
            $genderCorrection  = $req -> input('gender');
  

            switch($identifier){
                case 'firstname':
                    $profilefamilydemographics -> firstname = $firstnameCorrection;
                    break;
                case 'lastname':
                    $profilefamilydemographics ->lastname = $lastnameCorrection;
                    break;
                case 'age' :
                    $profilefamilydemographics -> age = $ageCorrection;
                    break;
                case 'gender':
                    $profilefamilydemographics ->gender = $genderCorrection;
                    break;
            }

            if($profilefamilydemographics){
                $profilefamilydemographics ->save();
                session() ->flash('notification', ['type' => 'success', 'message' => 'Profile updated  successfully']);
            } else {
             session()->flash('notification', ['type' => 'error', 'message' => 'An error occured while updating the profile ']);
            }
            return redirect() -> back();
            }
         }


@foreach($families as $family)
<div class="modal fade" id="FamilyDemographicsModel{{$family -> id }}" tabindex="-1" role="dialog" aria-labelledby="ModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="ModalLabel">Edit Profile</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">

                    <form action="{{ route ('SaveFamDemoEdits', ['id' => $family -> id])}}" method="POST" enctype="multipart/form-data"  id="FamilyDemographics{{$family -> id }}">
                        @method('PUT')
                        @csrf
                        <input type="hidden" id="editId" value="">
                        <div class="form-group">
                            <label for="editName">First Name</label>
                            <input type="text" name="name" class="form-control" id="editName" placeholder="First Name"  value="{{$family->firstname}}" required>
                        </div>
                        <div class="form-group">
                            <label for="editSurname">Last Name</label>
                            <input type="text" name="surname" class="form-control" id="editSurname" placeholder="Last Name" value="{{$family->lastname}}" required>
                        </div>
                        <div class="form-group">
                            <label for="editAge">Age</label>
                            <input type="number"  name="age" class="form-control" id="editAge" value="{{$family->age}}" required>
                        </div>
                        <div class="form-group">
                            <label for="editPhone">Gender </label>
                            <input type="text"  name="gender" class="form-control" id="editGender" value="{{$family->gender}}" required>
                        </div>
                        
                        <div class="modal-footer">
                            <a  class="btn btn-secondary" data-dismiss="modal">Close</a>
                            <button type="submit"  id="saveModalButton" class="btn btn-primary" >Save changes</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
@endforeach
<!-- pass existing data to the above modal-->
<script>
    $(document).ready(function() {
        $(document).on('click', '.edit-famdemo', function() {
            var identifier = $(this).data('identifier');
            var modalId = $(this).data('target');
            var familyId = $(this).data('familyid');

            var firstName = $(modalId).find('input[name="name"]').val();
            var lastName = $(modalId).find('input[name="surname"]').val();
            var age = $(modalId).find('input[name="age"]').val();
            var gender = $(modalId).find('input[name="gender"]').val();

            var fieldIdentifier = $(modalId).find('#editId').val(identifier);

            $(modalId + ' input[name="name"]').val(firstName);
            $(modalId + ' input[name="surname"]').val(lastName);
            $(modalId + ' input[name="age"]').val(age);
            $(modalId + ' input[name="gender"]').val(gender);

            $(modalId).data('field-identifier', fieldIdentifier);
        });
    });
</script>


the following is the link to open the modal based on which item we are going to edit

  <tbody>
                                       
                                         @foreach ($lessThan18 as $age => $records)
                                         @foreach ($records as $record)
                                        <tr>
                                        <td>{{ $record->firstname }}</td>
                                        <td>{{ $record->lastname }}</td>
                                        <td>{{ $record->age }}</td>
                                        <td>{{ $record->gender }}</td>
                                        <td>
                                              @include('modal')
                                                <a href="#" class="edit-famdemo" data-toggle="modal" data-target="#FamilyDemographicsModel{{$record->id}}" data-identifier="{{ $record->id }}" data-familyid="{{$record->id}}">
    <i class="bi bi-pencil-fill bluepen"></i>
</a> </td>
                                        </tr>
                                        @endforeach
                                        @endforeach
                                            
                                        </tbody>


here is my route

Route::put('SaveFamDemoEdits/{id}', [SaveProfileEditsController::class, 'SavefamdemoEdits']) -> name('SaveFamDemoEdits');
0 likes
26 replies
Tray2's avatar

I would start with a dd in your save method for starters.

 public function SavefamdemoEdits(Request $req, $id){

		dd($req);
         $profilefamilydemographics = FamilyDemographicsModel::find($id);

And make sure that it contains the data you need.

Tray2's avatar

@Danny971 Good then move the dd to this

dd($profilefamilydemographics);

And see if it finds any record, my guess is that it doesn't.

You really should use findOrFail() instead of just find;

Last tips, use camel case for your variable names, makes it much easier to read.

$profileFamilyDemographics
Snapey's avatar

why do you need an identifier to say which field is changing?

What if i change two fields?

Where is your validation?

Danny971's avatar

@Snapey the identifier is to see which item is being change . I havent put validation as yet

Danny971's avatar

@Snapey i put the identifier to be able to identify which item is being updated

Danny971's avatar

@Snapey The identifier is used to identify the specific field that is being edited within the modal. It helps determine which field's value needs to be updated in the controller.

In the code, the identifier is passed as a data attribute (data-identifier="{{ $record->id }}") to the "Edit" button in the table. When the "Edit" button is clicked, the JavaScript code retrieves the identifier value and assigns it to the hidden field editId in the modal form.

Later, when the form is submitted, the SaveFamDemoEdits route is called with the id parameter, which represents the identifier of the field being edited. This identifier is then used in the controller to determine which field's value should be updated based on the switch statement:

public function SavefamdemoEdits(Request $req, $id){
 
        
         $ProfileFamilyDemographics = FamilyDemographicsModel::find($id);

       

         if($ProfileFamilyDemographics) {

            $identifier = $req->input('identifier');

            $firstnameCorrection  = $req -> input('name');
            $lastnameCorrection  = $req -> input('surname');
            $ageCorrection  = $req -> input('age');
            $genderCorrection  = $req -> input('gender');
           

            switch($identifier){
                case 'firstname':
                    $ProfileFamilyDemographics -> firstname = $firstnameCorrection;
                    break;
                case 'lastname':
                    $ProfileFamilyDemographics ->lastname = $lastnameCorrection;
                    break;
                case 'age' :
                    $ProfileFamilyDemographics -> age = $ageCorrection;
                    break;
                case 'gender':
                    $ProfileFamilyDemographics->gender = $genderCorrection;
                    break;
            }

            if($ProfileFamilyDemographics){
                $ProfileFamilyDemographics ->save();
             
                session() ->flash('notification', ['type' => 'success', 'message' => 'Profile updated  successfully']);
            } else {
             session()->flash('notification', ['type' => 'error', 'message' => 'An error occured while updating the profile ']);
            }
            return redirect() -> back();
            }
         }
Snapey's avatar

Why would you want to restrict the user to only editing one field? Why can't they edit ANY of the fields at the same time? Why are you adding this artificial restriction?

Danny971's avatar

@Snapey because you can only edit one item at a time at a time .lets say we want to edit

Jon doe . we click edit next to jon doe and the modal appears with FirstName Jon last Name doe Age 8 gender Male and you can change any fields or all at once and click save cganges it suppose to update the db but in my case it doesnt

Snapey's avatar

@Danny971 but you are trying to use identifier so that only one field gets updated?

switch($identifier){
Danny971's avatar

@Snapey I used the identifer to get the id of the record we are trying to update

Tray2's avatar

@Danny971 So many things.

Consider this update method.

public function update(Game $game, GameFormRequest $request)
{
  $game->update($request->validated);

  return redirect(route('games.index'));
}

It uses route model binding to fetch the record from the database, and a form request for the validation.

The route would look like this.

Route::put('games/{game}', [GamesController::class, 'update')->name('games.update');

And the form request class like this

class GameFormRequest extends FormRequest
{
  public function rules(): array
  {
    return [
      'title' => ['required', 'string'],
      'release_year' => ['required'],
      'blurb' => ['required', 'string'],
      'genre_name' => ['required', 'string'],
      'format_name' => ['required', 'string'],
      'platform_name' => ['required', 'string'],
    ];
  }
}

You really don't need to write any custom code like you have done, I suggest reading the docs on Route model binding, form requests and validation.

Danny971's avatar

@Snapey yeah you're right . I knew this stuff been programming for a while and actually have a bachelors degree in com sci. I just run into a problem i posted it here. I actually understood the problem and know whats causing it. this is what causing it not to update ``` data-identifier="{{ $record->id }}"

. I am currently working on solving it . I changed it to data-identifier="firstname" and it worked it changed the Firstname however I am figuring out how to get the remaining three on board , namely : lastname,gender and age . I dont want to created a unique edit button for each based on the requirements so this is where I am now

Snapey's avatar

@Danny971 any normal non computer science degree developer would present the form with the current values and allow the user to change whatever fields they need to change, the save ALL the fields together

Your advanced training must tell you there is a better ux way where the user has to indicate which field they want to change and then in the backend you use that flag to know which field to write ?

Danny971's avatar

@Snapey so you saying that I should have an edit button for firstname, lastname,age , gender? IF yes then I would have accomplish that already . I am trying to have one edit button for each record

Snapey's avatar
Snapey
Best Answer
Level 122

@Danny971 you need to recognise the difference between record and field.

This code;

            switch($identifier){
                case 'firstname':
                    $ProfileFamilyDemographics -> firstname = $firstnameCorrection;
                    break;
                case 'lastname':
                    $ProfileFamilyDemographics ->lastname = $lastnameCorrection;
                    break;
                case 'age' :
                    $ProfileFamilyDemographics -> age = $ageCorrection;
                    break;
                case 'gender':
                    $ProfileFamilyDemographics->gender = $genderCorrection;
                    break;
            }

is trying to decide which of the FIELDS to update based on identifier

The RECORD that you want to edit is already passed into the controller as $id because you have a modal for every single row in your view (very inefficient)

You seem to have grabbed a bunch of ideas from different places and smushed them into one solution

Danny971's avatar

@Snapey a field refers has data about one aspect of the table , for example firstname and a record contains info about a particular person example ( firstname, lastname, age,gender ).

your statement : you have a modal for every single row in your view (very inefficient). I only have one modal for that. the modal has text field to edit first name ,last name, gender, age

your other statement: You seem to have grabbed a bunch of ideas from different places and smushed them into one solution. Nope i did not

Please or to participate in this conversation.