Lovelock
Lovelock

Reputation: 8075

Laravel 5 - Multiple form inputs with the same name but keeping the order

Making a blogging system using L5 and my current set up is all ready except for the saving of the blog posts.

I have 2 buttons. One creates a textarea input and the other creates a file upload interface.

Essentially, after creating a blog post I am left with the structure like so:

<form>
    <textarea name="text-update">foo</textarea>
    <textarea name="text-update">foo</textarea>
    <textarea name="text-update">foo</textarea>
    <textarea name="text-update">foo</textarea>
    <input type="hidden" value="an image url"/>
    <input type="hidden" value="an image url"/>
    <textarea name="text-update">foo</textarea>
</form>

Ideally I want to be able to go:

public function store()
{
    foreach (INPUTS AS INPUT) {
        add new row to database with the content and also the type of input.
    }
}

The aim is that instead of having a single blog I instead have blog sections which will belong to a blog post.

If this isn't possible then Ill just have to increment the names of the inputs and figure something out.

Upvotes: 2

Views: 16114

Answers (2)

jfadich
jfadich

Reputation: 6348

Edit: When you add an element to the DOM you can define the array key with an id to preserve the array order.

You can make the inputs an array by adding [] at the end of the name:

<form>
    <textarea name="text-update[1]">foo</textarea>
    <textarea name="text-update[2]">foo</textarea>
    <textarea name="text-update[3]">foo</textarea>
    <textarea name="text-update[4]">foo</textarea>
    <input type="hidden" name="image[1]" value="an image url"/>
    <input type="hidden" name="image[2]" value="an image url"/>
    <textarea name="text-update[5]">foo</textarea>
</form>

This will put all the values in an array that you can iterate over

foreach (Request::get('text-update') as $update) {
    //add new row to database with the content and also the type of input.
}
foreach (Request::get('image') as $update) {
    //add new row to database with the content and also the type of input.
}

Upvotes: 8

James Fannon
James Fannon

Reputation: 271

Set your fields up like this:

<textarea name="text-update[]">foo</textarea>

using the brackets will take all the text fields and group them into an array that you can then iterate through. You will also need to do the same with hidden fields. Make sure you use the [] in the name like so:

<input type="hidden" name="somename[]" value="an image url"/>

Upvotes: 3

Related Questions