Skip to content
Advertisement

Laravel foreach loop malfunctioning with old() data

I have a form that allows users to add a new row of inputs by clicking a button. For some reason on form submit (with a required row purposefully left empty to test form repopulation), index #1 is being skipped, and it happens every time the form is submitted. Also, extra rows are added on submit, and I can’t seem to figure out why.

Here is a numbered (top right) gallery depicting the result.

Foreach Loop:

JavaScript

jQuery:

JavaScript

Advertisement

Answer

This is likely due to how you’re looping the old data. Rather than looping through a subset of records specific for your table, you’re looping through the entire input data. Which you’ve already noticed, hence the conditional (if) checks to skip through keys you don’t need like _token.

Unfortunately, if an unwanted key like _token happens to be on the loop’s second run (index #1), nothing will be output and that row will be skipped. You can probably confirm this by confirming the output of old(), and seeing what order it’s in before rendering anything.

A couple better options might include:

  1. Looping through a known table value:

    JavaScript

    This targets only your “title” fields to count how many rows there are, but may produce inaccurate results if you allow titles to be blank and they aren’t received by your back end.

  2. Using nested structure naming for your form fields:

    JavaScript

    This may take a little more work to get your data just right, and possibly change your back end to work with the new hierarchy. It will, however, simplify your template logic:

    JavaScript

Pros and cons to each, use whichever suits your application or personal style the best. Either way, narrow in what data you’re looping and you’ll be successful. 🙂 Happy coding!

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement