我知道有人问过有关Laravel早期版本的问题,但我使用的是5.7.x(最新版本),因此5.2中的工作方式可能不适用于我的情况。基本上,我正在尝试创建一个通过自定义FormRequest验证的发布表单。这是我的源文件。
post.create.blade.php
<html>
@include('header')
<body>
<h1>Add a New Post</h1>
{!! Form::open(['route' => 'save_post']) !!}
<div class="form-group">
{!! Form::label('name', 'Name:') !!}
{!! Form::text('name', null) !!}
</div>
<div class="form-group">
{!! Form::label('body', 'Body:') !!}
{!! Form::textarea('body', null) !!}
</div>
{!! Form::submit('Create', ['class' => 'btn btn-info']) !!}
{!! Form::close() !!}
<div class="alert alert-danger">
<ul>
@if($errors->any())
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
@endif
</ul>
</div>
</body>
</html>
web.php
Route::get('post/create', function () {
return view('post_create');
});
PostController.php
<?php
namespace App\Http\Controllers;
use App\Post;
use App\Http\Requests\PostCreateRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Validator;
class PostController extends Controller
{
public function index()
{
return Post::paginate(1);
}
public function show($id)
{
return Post::find($id);
}
public function store(PostCreateRequest $request)
{
$post = Post::create($request->all());
$post->save();
return response()->json($post, 201);
}
public function update(Request $request, $id)
{
$post = Post::findOrFail($id);
$post->update($request->all());
return response()->json($post, 200);
}
public function delete(Request $request, $id)
{
$post = Post::findOrFail($id);
$post->delete();
return response()->json(null, 204);
}
PostCreateRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Foundation\Validation\ValidatesRequests;
class PostCreateRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name' => 'required|string|max:255',
'body' => 'required|string|max:4096'
];
}
}
显然,验证器正在工作。当我填写名称和正文时,它将在后端的SQL数据库中添加一个帖子。当失败时,它会返回到创建后视图。问题是,即使我已将其编码,验证器错误也不会显示在视图中。到底发生了什么? Laravel中是否存在某种错误?
更新:哦,万一有人好奇,我在用Ubuntu。一些消息来源暗示这曾经很重要。我不确定是否仍然如此。