0

I have two divs that have the same purpose but different values

<div id="tracks-1">
     <div>
        <label>Song Title</label>
         <input type="text" name="tracks[song_title]" value="">
         <input type="text" name="tracks[price]" value="">

     </div>
</div>

<div id="tracks-2">
     <div>
        <label>Song Title</label>
         <input type="text" name="tracks[song_title]" value="">
         <input type="text" name="tracks[price]" value="">
     </div>
</div>

when I submit it via post request Laravel I get the tracks data something like this

"tracks" => [
    "song_title" => "some title",
    "price" => "23"
    "song_title" => "some title 2",
    "price" => "25"
]

I want it Like this

"tracks" => [
   0 => ["song_title" => "some title", "price" => "23"],
   1 => ["song_title" => "some title 2", "price" => "25"]
]

Is there a way to do without javascript and JQuery

3
  • stackoverflow.com/a/5035796/10634638 Commented May 21, 2020 at 20:49
  • how your controller looks like? Commented May 27, 2020 at 3:32
  • You need to add one more array into the input name array like this - name="tracks[][song_title]" Commented Mar 14, 2024 at 11:19

2 Answers 2

0

If you remove the song_title reference from the name attributes in the form inputs to get an integer-indexed array...

<div id="tracks-1">
    <div>
        <label>Song Title</label>
        <input type="text" name="tracks[]" value="">
    </div>
</div>

<div id="tracks-2">
    <div>
        <label>Song Title</label>
        <input type="text" name="tracks[]" value="">
    </div>
</div>

Then you could use an array map on the posted form data like this in your post controller...

$tracks = array_map(function($trackTitle) {
    return ["song_title" => $trackTitle];
}, $_POST['tracks']);
Sign up to request clarification or add additional context in comments.

2 Comments

Don't mutate POST values. Store into a variable instead.
What if there are more input fields then?
-1

Try something like :

if $q = 1" { echo "song title }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.