I'm working with the Laravel framework, using eloquent for interacting with my database.
I have a form which I post to my controller. This form has 'tags' which are added by the user. The user can add as many tags as they want.
I want to POST the tags and then in my controller, insert each tag to a new table row, like so:
$tag = new Tag;
$tag->user_id = Input::get('user_id');
$tag->tag_name = Input::get('tag_name');
$tag->save();
How would I handle this? At first I thought put each tag into an array, POST the array, then in the controller i'd cycle through each element, inserting them into the database.
See the code here, this was actually a previous stack overflow question
But after some searching around I came to the conclusion that you cannot POST an array.
So the other way is to POST each array value as a hidden form type. The problem lies in how to tell my controller how many tags (and therefor rows) there are to insert.
I hope this is clear enough, thanks in advance.
EDIT: still having some trouble
EDIT 2: changed code to include 'i' variable in javascript and what the new array looks like when POSTed.
This is what the user generated input tag looks like
$("#tagsbox")
.append("<div class='displaytag'><i>"+tag+"</i><input type='hidden' name='tags["+i+"]["+user_id+"]' value="+user_id+"><input type='hidden' name='tags["+i+"]["+tag+"]'value="+tag+">")
This is what the POST data looks like after submission
Array
(
[user_id] => 12
[lat] => 50.80589
[lng] => -0.02784
[spot_name] => test spot
[tags] => Array
(
[1] => Array
(
[12] => 12
[tag1] => tag1
)
[2] => Array
(
[12] => 12
[tag2] => tag2
)
[3] => Array
(
[12] => 12
[tag3] => tag3
)
)
[location_notes] => some notes
[comments] => some comments
[_token] => Cfsx56FZiEKcVz76mkcZvuBtVG7JQSmdJUffFMfM
)
Controller stayed the same
//dynamic tags
$tags = Input::get('tags');
foreach ((array) $tags as $tagData)
{
// validate user_id and tag_name first
$tag = Tag::create(array_only($tagData, ['user_id', 'tag_name']));
}
//create spot
$spot = new Spot;
$spot->user_id = Input::get('user_id');
$spot->latitude = Input::get('lat');
$spot->longitude = Input::get('lng');
$spot->spot_name = Input::get('spot_name');
$spot->location_notes = Input::get('location_notes');
$spot->comments = Input::get('comments');
$spot->save();
return Redirect::route('home')
->with('global', 'Spot successfully tagged. You can edit all your spots on your profile.');
I still manage to get empty values in my database rows where there should be tags. Where am I going wrong?