【问题标题】:laravel validator not show errorslaravel 验证器不显示错误
【发布时间】:2016-06-28 18:25:41
【问题描述】:

我是 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 第 1 行中的 ErrorException:未定义变量:错误(查看:/www/alexey-laravel-1/resources/views/post/create.blade.php)

默认获取表单请求和从验证器重定向后出现此错误。

【问题讨论】:

    标签: php validation laravel-5


    【解决方案1】:

    要使$errors 在视图中可用,相关路由必须在web 中间件内:

    Route::group(['middleware' => ['web']], function () {
        Route::get('/post/', 'PostController@create');
        Route::post('/post/store', 'PostController@store');
    });
    

    【讨论】:

      猜你喜欢
      • 2018-12-05
      • 1970-01-01
      • 1970-01-01
      • 2016-08-17
      • 2012-12-14
      • 1970-01-01
      • 2019-12-31
      • 1970-01-01
      • 2020-04-28
      相关资源
      最近更新 更多