How to get the values for a series of checkboxes in Laravel 4 controller (if checked)

♀尐吖头ヾ 提交于 2019-12-30 03:07:10

问题


I would like to get the values for a series of checkboxes I have set up in a Laravel 4 form. Here is the code in the view setting up the checkboxes:

@foreach ($friends as $friend)
<input tabindex="1" type="checkbox" name="friend[]" id="{{$friend}}" value="{{$friend}}">
@endforeach

In my controller, I would like to get the values for the checked boxes and put them in an array. I am not exactly sure how to do this, but I assume it is something like:

array[];

foreach($friend as $x)
if (isset(Input::get('friend')) {
        array[] = Input::get('friend');

 } 
endforeach

Could you provide me with a solution to do this? Thank you.

EDIT:

This is what I have in the controller:

public function describe_favorite() {

            $fan = Fan::find(Auth::user()->id);
            $fan->favorite_venue = Input::get('venue');
            $fan->favorite_experience = Input::get('experience');

            $friends_checked = Input::get('friend[]');

            print_r($friends_checked);

            if(is_array($friends_checked))
            {
             $fan->experience_friends = 5;
            }

            $fan->save();


            return Redirect::to('fans/home');

        }

It is not going through the "if" loop. How do I see the output of the print_r to see what's in the $friends_checked variable?


回答1:


If checkboxes are related then you should use [] in the name attribute.

@foreach ($friends as $friend)
<input tabindex="1" type="checkbox" name="friend[]" id="{{$friend}}" value="{{$friend}}">
@endforeach


$friends_checked = Input::get('friend');
if(is_array($friends_checked))
{
   // do stuff with checked friends
}



回答2:


The array friend must have a key . If there is $friend->id you could try something like this.

 @foreach ($friends as $friend)
  <input tabindex="1" type="checkbox" name="friend[{{$friend->id}}]" id="{{$friend}}">
 @endforeach



回答3:


Using name="friend[]" in the form field creates an array named friend that is passed to the server, as opposed to name="friend" which passes a string value to the server.



来源:https://stackoverflow.com/questions/19235910/how-to-get-the-values-for-a-series-of-checkboxes-in-laravel-4-controller-if-che

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!