我是Laravel和其他PHP框架的新手。
尝试简单的表单并进行验证,例如https://laravel.com/docs/5.1/validation
中的示例routes.php文件
Route::get('/post/', 'PostController@create');
Route::post('/post/store', 'PostController@store');
create.blade.php
<html>
<head>
<title>Post form</title>
</head>
<body>
<h1>Create Post</h1>
<form action="/post/store" method="POST">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label for="title">Title</label>
<input type="text" id="title" name='title'>
</div>
<button type="submit" class="btn btn-default">Save</button>
</form>
</body>
PostController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use View;
use Validator;
class PostController extends Controller
{
/**
* Show the form to create a new blog post.
*
* @return Response
*/
public function create()
{
return view('post.create');
}
/**
* Store a new blog post.
*
* @param Request $request
* @return Response
*/
public function store(Request $request)
{
// Validate and store the blog post...
$validator = Validator::make($request->all(), [
'title' => 'required|min:5'
]);
if ($validator->fails()) {
dd($validator->errors);
//return redirect('post')
//->withErrors($validator)
//->withInput();
}
}
}
当我发布无效数据时:
PostController.php第37行中的ErrorException:未定义的属性:Illuminate \ Validation \ Validator :: $ errors
Validator对象也没有错误。
如果在控制器中启用
return redirect('post')->withErrors($validator)
->withInput();
并以表格
启用@if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
有错误
c5df03aa6445eda15ddf9d4b3d08e7882dfe13e1.php中的ErrorException第1行:未定义的变量:errors(查看:/www/alexey-laravel-1/resources/views/post/create.blade.php)
此错误在默认情况下获取表单请求以及从验证程序重定向之后。
答案 0 :(得分:0)
要使$errors
在视图中可用,相关路由必须位于web
中间件中:
Route::group(['middleware' => ['web']], function () {
Route::get('/post/', 'PostController@create');
Route::post('/post/store', 'PostController@store');
});