【问题标题】:Laravel 5.6 - Form not re-populating with previous values after validationLaravel 5.6 - 验证后表单未重新填充以前的值
【发布时间】:2018-12-09 20:18:55
【问题描述】:

我在 Laravel 5.6 中有一个简单的表单,我正在运行验证,我的表单看起来像这样..

   @if ($errors->any())
        <div class="alert alert-danger">
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif

<form action="{{route('posts.store')}}" method="POST">
   <input name="title" type="text">#
    <button type="submit" class="btn btn-success">Submit</button>
</form>

我的控制器也是这样的..

public function store(Request $request)
    {

        $this->validate($request, [
            'title' => 'required',
        ]);

        $post = new Post;
        $title = $request->input('title');
        $post->save();
    }

这是可行的,但是当验证失败并显示错误消息时,它不会使用以前的值重新填充表单。阅读https://laravel.com/docs/5.2/requests#old-input 的文档,它说我不应该做任何事情,它将是自动的。

有人知道我哪里出错了吗?

【问题讨论】:

    标签: php laravel laravel-5


    【解决方案1】:

    你没有在你的观点中呼应一个价值观。我 99% 确定以下检查 isset()。

    <input name="title" type="text" value="{{$name}}">#
    

    只需确保 $request-&gt;name 从您的控制器传递到您的视图,尽管这可能只是您所说的“自动化”部分......我必须检查文档。

    【讨论】:

    • 一旦你使用了 {{$name}},它只会调用从模型传递给该变量的值,而不一定是该表单输入中的旧值。要让表单返回旧值,请使用 value="{{ old('title') }}"
    【解决方案2】:

    如果您想保留以前的输入,则需要使用old helper function,如果您向下滚动到“检索旧输入”,请参阅链接文档。

    您需要将您的input 更改为以下内容:

    <input name="title" type="text" value="{{ old('title') }}">
    

    其中title 与您输入的name 属性中的值匹配。

    【讨论】:

    • 谢谢你,老工作完美。现在开始阅读
    猜你喜欢
    • 1970-01-01
    • 2010-11-10
    • 1970-01-01
    • 2019-05-13
    • 1970-01-01
    • 1970-01-01
    • 2018-04-11
    • 2010-12-30
    • 1970-01-01
    相关资源
    最近更新 更多