首页 > 解决方案 > Laravel 5.4 $error 未显示/闪烁

问题描述

我使用 vagrant for windows 全新安装了 Laravel 5.4。

现在,当我按照 laracast 中的 tuts 并尝试表单验证时,一切都很好,但$errors变量根本不包含任何错误消息。

片段来自PostsController

public function store()
{
    $this->validate(request(), [
        'title' => 'required|unique:posts,title|min:3',
        'body' => 'required'
    ]);

    Post::firstOrCreate(request(['title', 'body']));

    return redirect()->route('create-post');
}

我的create.blade.php的片段

@extends('layout')

@section('content')
<main role="main" class="container">

    <div class="row">

        <div class="col-md-8 blog-main">
            <h3 class="pb-3 mb-4 font-italic border-bottom">
                Create Post Form
            </h3>


            <form action="/api/posts" method="POST">

                {{ csrf_field() }}

                <div class="form-group">
                    <label for="title">Title</label>
                    <input type="text" class="form-control" id="title" placeholder="Title" name="title" value="">
                    <small class="text-danger">{{ $errors->first('title') }}</small>
                </div>

                <div class="form-group">
                    <label for="body">Content</label>
                    <textarea class="form-control" id="body" rows="5" name="body" placeholder="Contents Here.." value=""></textarea>
                    <small class="text-danger">{{ $errors->first('body') }}</small>
                </div>

                <div class="form-group">
                    <button class="btn btn-primary" type="submit">Submit</button>
                </div>

                <div class="form-group">
                    <div class="alert alert-{{ $errors->any() ? 'danger' : 'default' }}">
                        <ul>
                            @foreach($errors->all() as $error)
                                <li>{{ $error }}</li>
                            @endforeach
                        </ul>
                    </div>
                </div>
            </form>

        </div>

        @include('partials.sidebar')

    </div>

</main>
@endsection

验证失败后的结果

errors_no_showing

我有什么遗漏或有什么问题吗?

编辑

这是我的路线片段:

Route::get('/', 'PostsController@index');
Route::get('/posts/{post}', 'PostsController@show');

Route::get('/create', function() {
   return view('posts.create');
})->name('create-post');

Route::post('/posts', 'PostsController@store');

标签: phplaravellaravel-5.4

解决方案


找到了答案。

因为它是 5.4,所以我没有注意到所有的 web.php 都在一个名为web的中间件下

其中包括\Illuminate\View\Middleware\ShareErrorsFromSession::class

我的api/postsapi中间件上,这就是为什么没有任何会话共享的原因。

这个链接也帮助解决了这个问题。

Laravel 5.2 $errors 未出现在 Blade 中


推荐阅读