Laravel复选框验证,总是空的?

时间:2017-09-26 15:05:45

标签: laravel laravel-5 laravel-validation laravel-5.5

我有一个像这样的复选框:

<div class="form-group">
  <div style="display:none ;" class="weekday_message form-control alert-warning"></div>
  <label id="weekday2" for="weekday" class="col-md-4 control-label">Weekday</label>
  <div class="required form-field" name="weekday" id="weekday">
    <input class="weekday" type="checkbox" name="weekdays[]" value="MO">Monday
    <input class="weekday" type="checkbox" name="weekdays[]" value="TU">Tuesday
    <input class="weekday" type="checkbox" name="weekdays[]" value="WE">Wednesday
    <input class="weekday" type="checkbox" name="weekdays[]" value="TH">Thursday
    <input class="weekday" type="checkbox" name="weekdays[]" value="FR">Friday
    <input class="weekday" type="checkbox" name="weekdays[]" value="SA">Saturday
    <input class="weekday" type="checkbox" name="weekdays[]" value="SU">Sunday
  </div>
    <span class="help-block">
        <strong></strong>
</span>
  </div>

我的验证:

public function rules()
    {
        return [
            'startdate' => 'required|date',
            'endate' => 'nullable|date',
            'startime' => ['required', new Time],
            'endtime' => ['required', new Time],
            'title' => 'required',
            'entity_id' => 'required',
            'type' => 'required|exists:entities,type',
            'description' => 'required',
            'frequency' => 'required',
            'interval' => 'nullable|numeric',
            'monthday' => 'nullable|numeric|min:1|max:3',
            'weekdays' => 'array|max:3',
            'month' => 'nullable|numeric',
            'until' => 'nullable|date',
            'tags' => 'nullable',
        ];
    }

和控制器:

public function storeEvent(EventRequest $request)
{
    $test = ($request->input('weekdays'));
    dd($test);
    $weekday_string = implode(",", $request->input('weekdays'));
    $request->merge(array('weekday', $weekday_string));
    dd($request->all());
    $event = DirtyEvent::create($request->all());
    $geoloc_id = Entity::find($event->entity_id)
        ->first();
    $user_id = Auth::id();
    // Save Geoloc + user id into newly created event
    $event->_geoloc()->associate($geoloc_id);
    $event->users()->associate($user_id);
    $event->save();

现在,验证似乎已经过去了,因为它会进行数据转储,但是dd($ test)以及$ request-&gt; all()都会让我回到空白的工作日,就像它不会被定义一样。可能的原因是什么?

2 个答案:

答案 0 :(得分:0)

如果您想确保始终至少选择一个工作日,则应更改:

'weekdays' => 'array|max:3',

成:

'weekdays' => 'array|required|max:3',

此外,我认为您不使用标准HTML表单发送数据,因为您为div设置了示例名称​​,因此您可能忘记在工作日附加工作日或在其他地方出现代码错误?

答案 1 :(得分:0)

您的HTML说weekday(单数),但您的规则集是weekdays(复数)。

必须至少选中一个复选框才能使输入weekdays包含在请求中。如果没有选中,则可以通过在复选框之前添加隐藏输入来使用默认值。

<input type="hidden" name="weekdays" value="defaultValue">