首页 > 解决方案 > 使用 laravel 通过更新请求验证后,如何维护复选框中的旧输入值?

问题描述

当我打开编辑页面时,它应该具有来自数据库的值,当我更改值时,如果验证失败,我需要保持 {{old('input')}} 值。这是代码:

<input type="checkbox" id="show_in_website" name="show_in_website"  @if($data->show_in_website=='1') checked @endif>Show in Website
       

标签: phplaravelvalidationinputcheckbox

解决方案


您可以使用old()辅助方法。辅助方法支持在old()验证失败时检索任何旧表单值。此外,它允许在空/空上传递默认值,这意味着我们可以在最初调用编辑页面时将数据库中的值作为默认值传递。

<input type="checkbox" id="show_in_website" name="show_in_website" {{ old('show_in_website', $data->show_in_website) ? 'checked' : '' }}> Show in Website

另外,请确保您使用以下方式重定向回表单withInput()

if($validator->fails()) {
    return back()->withErrors($validator)->withInput();
} 

推荐阅读