没有从表单中获取复选框元素值

时间:2017-08-30 18:33:49

标签: laravel

我在Laravel 5.4中有一个小表单,它有一个复选框和一个文本框。问题是,当我发布表单时,复选框值不会通过请求。我在复选框上有自定义样式但肯定不是那个?

我一直在看这个问题,一切看起来都很正常。我的代码如下:

<form method="post" action="{{ route('admin.settings.save') }}">
    {{ csrf_field() }}
    <div class="row">
        <div class="col-md-6">
            <div class="form-group">
                <label><b>Site Name</b></label>
                <p>This is the name of your LaravelFileManager instance.</p>
                <input name="siteName" id="siteName" class="form-control" value="{{ \App\Helpers\ConfigHelper::getValue('site_name') }}" />
            </div>

            <div class="form-group">
                <label><b>Footer Message</b></label>
                <p>You can customise the footer message for the application.</p>
                <div class="checkbox">
                    <label>
                        <input type="checkbox" name="showFooter" id="showFooter" checked="{{ \App\Helpers\ConfigHelper::getValue('show_footer_message') }}"> Show footer message
                    </label>
                </div>
            </div>

            <button type="submit" class="btn btn-success"><i class="fa fa-save"></i>&nbsp;&nbsp;Save Changes</button>
        </div>
    </div>
</form>

我的控制器代码是这样的:

public function saveSettings(Request $request) {
    $siteName = $request->input('siteName');
    $showFooter = $request->input('showFooter');

    ConfigHelper::setValue('site_name', $siteName);
    ConfigHelper::setValue('show_footer_message', $showFooter);

    return redirect()->route('admin.settings')->with('result', 'Settings saved.');
}

我的路线:

Route::post('settings/save', ['uses' => 'Admin\SettingsController@saveSettings'])->name('admin.settings.save');

我还在$ request变量上做了一个vardump,甚至错过了复选框值:

array(2) { 
    ["_token"]=> string(40) "sgyO7Kkz1ljsYEZ1G5nkj4uVbmFZqiTMbpK9P6Bi" 
    ["siteName"]=> string(16) "File Manager 1.0" 
}

它缺少'showFooter'变量。

不太确定该去哪儿。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:2)

所以我最终得到了这个。使用评论中的帮助:

public function saveSettings(Request $request) {
    $siteName = $request->input('siteName');
    $showFooter = $request->has('showFooter');

    ConfigHelper::setValue('site_name', $siteName);
    ConfigHelper::setValue('show_footer_message', $showFooter);

    return redirect()->route('admin.settings')->with('result', 'Settings saved.');
}

出于某种原因,使用$request->input('showFooter')并未正常工作。 $request->get('showFooter')在结果为true时会显示结果,因此添加三元组会使其每次都有效。