从Laravel 5中的复选框获取值

时间:2016-12-29 02:35:21

标签: php laravel checkbox laravel-5

我正在我的网站上处理报价申请表,需要一些功能方面的帮助。我试图从我传递给视图的一组复选框中获取值;像这样:

控制器(getQuote)

public function getQuote()
    {

      $services = array(
        'Accept donations',
        'Update website on your own',
        'E-Commerce',
        ...
      );

        return view('pages.quote')->withServices($services);

    }

控制器(postQuote)

public function postQuote(Request $request)
    {
      $this->validate($request, [
        'services' => 'required|array',
        ...
      ]);


      $data = array(
        'services' => $request->service,
        ...
      );

      $data['services_checked'] = Input::get('service');
      if(is_array($services_checked))
      {
      }

      Mail::send('emails.quote', $data, function($message) use ($data){
        $message->from($data['email']);
        $message->to('hi@sogenius.io');
        $message->subject('New quote request for ' .  $data['firstname'] . ' ' . $data['lastname']);

      });

      return redirect()->back()->with('message', "Thanks, your quote request has been sent");

    }

查看

然后我遍历传递的数组中的值并将其显示给用户。

<article class="col-md-12 text-left services bx1-margin">
                {{ Form::label('services', "Please check all the functionality you would like to see in your new website:") }}

                {{-- <label for="services">Please check all the functionality you would like to see in your new website.</label> --}}
                <ul>
                @foreach ($services as $servicesid => $service)
                  <li>
                    {{-- {{ Form::checkbox('agree', 1, true) }} --}}
                    <input id="{{$servicesid}}" value="{{$servicesid}}" name="service[{{$servicesid}}]" type="checkbox" class="custom-control-input form-check-input">
                    <span class="custom-control-description">{{$service}}</span>
                    {{-- <input id="s-{{$servicesid}}" name="services" type="checkbox" class="custom-control-input form-check-input"> --}}


                  </li>
                @endforeach
                </ul>
              </article>

当用户提交表单时,如何接收选中的复选框?

研究

我在这里看到了这篇文章:How to get the values for a series of checkboxes in Laravel 4 controller (if checked)我看到了她的(stackoverflow)帖子,它解释了将值设置为array[],我对实施情况不太确定。

1 个答案:

答案 0 :(得分:2)

确保类型为input的{​​{1}}使用与html表单中checkbox相同的名称

services[]

因此,当您提交时,只需检查<input id="{{$servicesid}}" value="{{$servicesid}}" name="service[]" type="checkbox" class="custom-control-input form-check-input"> 方法中的变量$request->service即可。它应该包含提交了所有已检查输入的数组变量。