How to Retrieve Data from an HTML Table using the Laravel Framework

I have a unique and interactive Dynamic Sortable Table where I can effortlessly add or delete rows likethis uploaded image here. There is an intriguing loop in my controller that runs precisely 4 times, based on the number of columns in the table. However, the column number remains fixed while the row number varies. My objective is to alter this loop to run based on the number of rows in the table. Here is how my view page looks:

{!! Form::open(['action' => 'WorkBreakdownController@store', 'method' => 'POST', 'enctype' => 'multipart/form-data']) !!}
<table class="table table-hover table-sortable" id="tab_logic" name="DataTable">
                                <thead>
                                    <tr class="text-center">
                                        <td style="width: 40%;">Process Name</td>
                                        <td style="width: 30%;">Machine Name</td>
                                        <td style="width: 10%;">Machine Qty</td>
                                        <td style="width: 10%;">SMV</td>
                                        <td style="width: 10%;">Action</td>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr id='addr0' data-id="0" class="hidden">
                                        <td data-name="ProcessName">
                                            {{Form::text('items[][ProcessName]', '', ['id'=>'ProcessName', 'class' => 'form-control', 'placeholder'=>''])}}
                                        </td>
                                        <td data-name="MachineName">
                                            <div class="form-group row-fluid m-auto">
                                                <select name="items[][MachineName]" class="form-control" id="MachineName" data-live-search="true">
                                                    <option value=""></option>
                                                    @foreach($machineName as $machine)
                                                        <option value="{{$machine->id}}">{{$machine->MachineName}}</option>
                                                    @endforeach
                                                </select>
                                            </div>
                                        </td>
                                        <td data-name="MachineQty">
                                        {{Form::number('items[][MachineQty]', '', ['id'=>'MachineQty', 'class' => 'form-control', 'placeholder'=>''])}}
                                        </td>
                                        <td data-name="SMV">
                                        {{Form::number('items[][SMV]', '', ['id'=>'SMV', 'class' => 'form-control', 'placeholder'=>''])}}
                                        </td>
                                        <td data-name="del">
                                            <a name="del0" id="del0" class="btn btn-outline-danger row-remove"  value="del0">Delete</a>                        
                                            {{-- <button name="del0" class='btn btn-outline-danger row-remove'>Delete</button> --}}
                                        </td>
                                    </tr>
                                </tbody>
                                
                                <tfoot>
                                    <tr>
                                        <td colspan="5" style="text-align: left;">
                                            <a id="add_row" class="btn float-right btn-lg btn-block btn-outline-secondary">Add Row</a>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td colspan="5" style="text-align: left;">
                                            {{Form::submit('Save', ['class'=>'btn btn-lg btn-outline-primary btn-block', 'name'=>'ProductInsert'])}}
                                        </td>
                                    </tr>
                                </tfoot>
                            </table>

Below is the snippet of code from the controller:

$j=0;
            // $ProcessName_ID = $request->input('MachineName');
            foreach($request->input('items', []) as $item){
            $work_breakdown = new work_breakdown($item);
            $work_breakdown->SN = $j;
            $work_breakdown->ProcessName = $request->input("ProcessName{$j}");
            $work_breakdown->MachineID = $request->input("MachineName{$j}");
            $work_breakdown->MachineQty = $request["MachineQty{$j}"];
            $work_breakdown->SMV = $request["SMV{$j}"];
            $work_breakdown->user_id = auth()->user()->id;
            $work_breakdown->save(); 
            $j++;
            }

Surprisingly, this loop iterates exactly 4 times and no more than that.

Answer №1

In order to ensure that the text data is correctly stored without any images, and assuming that your ajax post call is accurate, you can implement the following store function within your controller:

public function store(Request $request) {
  // For demonstration purposes I have referred to it as the 'device' model, but please replace it with the appropriate model name
  $device = Device::create($request->all());

  if($device) {
    return redirect()->route('device.index')->with('message', 'Success'); // Redirect to device/index.blade.php along with a success message
  }

  return redirect()->route('device.index')->with('message', 'error'); // Redirect to device/index.blade.php along with an error message

}

Answer №2

I have come up with a unique solution to solve this problem. If anyone is aware of the conventional approach, please share it with me. Here's how I modified my view page:

<table class="custom-table custom-sortable" id="tab_logic"">
                                <thead>
                                    <tr class="text-center">
                                        <td style="width: 2%;" class="text-white">Serial Number</td>
                                        <td style="width: 38%;">Process Name</td>
                                        <td style="width: 30%;">Machine Name</td>
                                        <td style="width: 10%;">Machine Quantity</td>
                                        <td style="width: 10%;">SMV</td>
                                        <td style="width: 10%;">Action</td>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr id='row0' data-id="0" class="hidden-row">
                                        <td data-name="serialNumber" class="hidden-data">
                                            <div class="form-group row-fluid m-auto">
                                            <input name="items[][serialNumber]" type="text" class="form-control hidden-input" id="autoIncrementRow">
                                            </div>
                                        </td>
                                        <td data-name="processName">
                                            {{Form::text('processName0', '', ['id'=>'processName', 'class' => 'form-control', 'placeholder'=>''])}}
                                        </td>
                                        <td data-name="machineName">
                                                <select name="machineName0" class="form-control row-fluid m-auto" id="machineName" data-live-search="true">
                                                    <option value=""></option>
                                                    @foreach($machines as $machine)
                                                        <option value="{{$machine->id}}">{{$machine->name}}</option>
                                                    @endforeach
                                                </select>
                                        </td>
                                        <td data-name="machineQty">
                                        {{Form::number('machineQty0', '', ['id'=>'machineQty', 'class' => 'form-control', 'placeholder'=>''])}}
                                        </td>
                                        <td data-name="smv">
                                        {{Form::number('SMV0', '', ['id'=>'SMV', 'class' => 'form-control', 'placeholder'=>''])}}
                                        </td>
                                        <td data-name="delete">
                                            <a name="delete0" id="delete0" class="btn btn-outline-danger row-remove"  value="delete0">Delete</a>                        
                                            {{-- <button name="delete0" class='btn btn-outline-danger row-remove'>Delete</button> --}}
                                        </td>
                                    </tr>
                                </tbody>
                                
                                <tfoot>
                                    <tr>
                                        <td colspan="6" style="text-align: left;">
                                            <a id="add_row" class="btn float-right btn-lg btn-block btn-outline-secondary">Add Row</a>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td colspan="6" style="text-align: left;">
                                            {{Form::submit('Save', ['class'=>'btn btn-lg btn-outline-primary btn-block', 'name'=>'ProductInsert'])}}
                                        </td>
                                    </tr>
                                </tfoot>
                            </table>

Now let's take a look at the controller:

$maxID = product_details::max('id');
            $i=0;
            $j=0;
            foreach($request->input('items', []) as $item){
            
            $j++;
            // Create Post
            $work_breakdown = new work_breakdown($item);
            $work_breakdown->productId = $maxID;
            $work_breakdown->serialNumber = $j;
            $work_breakdown->processName = $request->input("processName{$j}");
            $work_breakdown->machineId = $request->input("machineName{$j}");
            $work_breakdown->machineQty = $request["machineQty{$j}"];
            $work_breakdown->smv = $request["SMV{$j}"];
            $work_breakdown->userId = auth()->user()->id;
            $work_breakdown->save(); 
            }

            $userID = auth()->user()->id;
            

            // Delete extra row
            $maxID2 = work_breakdown::where('userId', $userID)->max('id');
            DB::delete('delete from work_breakdown where id = ?',[$maxID2]);

This loop always saves an additional row with null values, so I delete it after the loop execution.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

- Prefixing with -webkit-transform and overlooking z-index

When using Safari 5.1.7 on Windows, I noticed that some rotated elements are overlapping others: However, when I test it on Firefox, Chrome, and IE, the issue doesn't occur: Is there a solution to prevent this overlap problem specifically on Safari? ...

Is this code in line with commonly accepted norms and standards in Javascript and HTML?

Check out this Javascript Quiz script I created: /* Jane Doe. 2022. */ var Questions = [ { Question: "What is 5+2?", Values: ["7", "9", "10", "6"], Answer: 1 }, { Question: "What is the square root of 16?", Values: ["7", "5", "4", "1"], Answer: ...

Tap on the child to reveal their parent

I am working with a family tree that includes dropdown menus containing the names of parents and children. Each child has a link, and when I click on a child's link, I want their father to be displayed in the dropdown menu as the selected option. Can ...

Adjusting the height of flex items to 100%

I'm currently diving into the world of flexbox by exploring various tutorials. Here's an example I created without utilizing Flex. Instead, I relied on float:left. Check out the example: https://jsfiddle.net/arhj8wxg/4/ I attempted to convert t ...

Place two anchors side by side using inline-blocks without using the float property

Is there a way to align two buttons next to each other without using floating? I have encountered an issue where adding a width to one of the buttons causes it to jump down and be on a different line than the other button. The buttons are centered, so th ...

Issues persist with jQuery ajax request attempting to retrieve data from database

I attempted to retrieve data from my database using jQuery AJAX. Below is the code snippet I used: <script> $(document).ready(function(){ function fetch_data(){ $.ajax({ type:"POST", url:"http://localhost:88/phpPoint/select.php", success:function(re ...

Retrieve the browser version of a client using C# (When Internet Explorer Compatibility mode is activated)

Is there a way to retrieve the actual version of the client's browser from C# code? Using Request.Browser or HTTP_USER_AGENT provides details, but in Internet Explorer (IE), when compatibility mode is enabled, it always returns IE 7 regardless of the ...

What is the reason that when we assign `'initial'` as the value for `display` property, it does not function as intended for list elements?

To toggle the visibility of elements, I have created a unique function that accepts an object and a boolean. Depending on the boolean value, either 'none' or 'initial' is assigned to the 'display' property of the specified obj ...

What is causing the radio button's background color not to change after it is selected?

I've been searching and exploring various solutions, but I'm encountering some difficulties with the following scenario: There are a few restrictions: Cannot utilize Javascript or Jquery. Must be achieved using pure CSS. My objective is to chan ...

The interaction between an iOS application and a Laravel web application

Currently, I am in the process of developing a project that involves an iOS app utilizing a webapp built on the Laravel framework for communication. For instance, iOS users will need to use the Laravel login in order to access the application. The Laravel ...

The web forms on my shared hosting account are set up to send emails via SMTP to my designated email address, but they are unable to send to providers such as Gmail

After conducting a search, I am still struggling to find the right solution... I have encountered an issue with setting up web forms using Node.js (express) and PHP. The problem lies in sending form data to email addresses outside of my domain. Despite su ...

PHP Error in Syntax

Earlier, I posted a question with a partial explanation. However, here is the complete version of my issue. I keep encountering a Syntax Error that gets resolved when I remove a specific block of code. There seems to be an underlying problem here, but desp ...

Tips for presenting a label and its value on separate lines while also displaying additional nested label-value pairs:

I have a specific request in mind, But the result I am seeing is different, Here's the code snippet, I'm utilizing bulma framework but encountering some challenges... <section class="section"> <p>Please verify the details below a ...

Bootswatch is causing the Bootstrap tooltip feature to malfunction

Could someone help me figure out why my tooltip isn't functioning properly? The HTML Code in Question: <div class="form-check"> <label class="form-check-label" > <input type="radio" class="form-check-input" name= ...

Utilizing var_export() to display the sorted array

I have this array in my p.e. assignment that needs to be sorted based on specific criteria before outputting the result using var_export(). $array = [ 'hello', 'internet', 'people' ]; The sorting code must ...

Save picture in localStorage

Hello, I am currently working on a page where I need to retrieve an image from a JSON file and store it locally. Below is the code I have been using: <!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-1.10.1.min. ...

What is the best way to use a variable as a key in PHP's $_POST array

Is it possible to pass a variable as the key value in the $_POST array in PHP? $example = "example"; echo $_POST[$example]; Appreciate your help! ...

Stop the recurrence of multiple clicks by incorporating a Bootstrap modal popup confirmation

$('button[name="remove_levels"]').on('click', function (e) { var $form = $(this).closest('form'); e.preventDefault(); $('#confirm').modal({ backdrop: 'static', ...

Need to transfer data from an Angular 5 application to a server-side file using PHP, but

I am experimenting with sending an encrypted variable from Angular to a PHP script for testing purposes. Below is the client-side script: ngOnInit(){ let user = "am"; let key = "pizza"; let enc = crypto.AES.encrypt(user, key); console.log(enc); let dec = ...

What is the best way to fetch values from individual buttons using PHP?

<form action="posts-ayarlar.php" method="POST" id="demo-form2" data-parsley-validate class="form-horizontal form-label-left"> <table class="table table-striped table-bordered" ...