Laravel 5.2 验证错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34420590/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 17:12:19  来源:igfitidea点击:

Laravel 5.2 validation errors

laravellaravel-validationlaravel-5.2

提问by Dmitry

I have some trouble with validation in Laravel 5.2 When i try validate request in controller like this

我在 Laravel 5.2 中进行验证时遇到了一些麻烦当我像这样在控制器中尝试验证请求时

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

Validator catch error, but don't store them to session, so when i'm try to call in template this code

验证器捕获错误,但不要将它们存储到会话中,因此当我尝试在模板中调用此代码时

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

Laravel throw the error

Laravel 抛出错误

Undefined variable: errors (View: /home/vagrant/Code/os.dev/resources/views/semantic/index.blade.php)

When i'm try validate with this code

当我尝试使用此代码进行验证时

 $validator = Validator::make($request->all(), [
                'title' => 'required',
                'content.*.rate' => 'required'
            ]);

            if ($validator->fails()) {
                return redirect()
                    ->back()
                    ->withInput($request->all())
                    ->withErrors($validator, 'error');
            }

Variable $error also not available in template but if i try to display errors in controller

变量 $error 在模板中也不可用,但如果我尝试在控制器中显示错误

   if ($validator->fails()) {
                dd($validator->errors()->all());
            }

Errors displays but i can't access to them from template.

错误显示,但我无法从模板访问它们。

What's wrong?

怎么了?

回答by Thomas Kim

Update as of Laravel 5.2.27

从 Laravel 5.2.27 开始更新

Laravel now supports the web middleware by default as you can see here: source

Laravel 现在默认支持 web 中间件,你可以在这里看到:source

In other words, you no longer need to wrap your routes around the web middleware group because it does it for you in the RouteServiceProvider file. However, if you are using a version of Laravel between 5.2.0 and 5.2.26, then refer to the method below:

换句话说,您不再需要将您的路由包裹在 web 中间件组周围,因为它在 RouteServiceProvider 文件中为您完成。但是,如果您使用的是 5.2.0 和 5.2.26 之间的 Laravel 版本,则参考以下方法:

Below only applies to Laravel 5.2.0 to 5.2.26

以下仅适用于 Laravel 5.2.0 至 5.2.26

Without seeing your routes.phpor Kernel.phpfile, here is what I suspect is happening.

没有看到您的routes.phpKernel.php文件,这就是我怀疑正在发生的事情。

The way middlewares work has changed from 5.2 and 5.1. In 5.1, you will see this in your app/Http/Kernel.phpfile:

中间件的工作方式从 5.2 和 5.1 改变了。在 5.1 中,您将在app/Http/Kernel.php文件中看到:

protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \App\Http\Middleware\EncryptCookies::class,
    \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    \App\Http\Middleware\VerifyCsrfToken::class,
];

This array is your application's global HTTP middleware stack. In other words, they run on everyrequest. Take a note at this particular middleware: Illuminate\View\Middleware\ShareErrorsFromSession. This is what adds the $errorsvariable on every request.

此数组是您的应用程序的全局 HTTP 中间件堆栈。换句话说,它们在每个请求上运行。请注意这个特定的中间件:Illuminate\View\Middleware\ShareErrorsFromSession. 这就是$errors在每个请求上添加变量的原因。

However, in 5.2, things have changed to allow for both a web UI and an API within the same application. Now, you will see this in that same file:

但是,在 5.2 中,情况发生了变化,允许在同一应用程序中同时使用 Web UI 和 API。现在,您将在同一个文件中看到:

protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
];

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
    ],

    'api' => [
        'throttle:60,1',
    ],
];

The global middleware stack now only checks for maintenance. You now have a middleware group called "web" that includes a bulk of the previous global middleware. Remember that it is like this to allow for both a web UI and an API within the same application.

全局中间件堆栈现在只检查维护。您现在拥有一个名为“web”的中间件组,其中包含大量以前的全局中间件。请记住,允许在同一应用程序中同时使用 Web UI 和 API 就是这样。

So how do we get that $errorsvariable back?

那么我们如何取回那个$errors变量呢?

In your routes file, you need to add your routes within the "web" middleware group for you to have access to that $errorsvariable on every request. Like this:

在您的路由文件中,您需要在“web”中间件组中添加您的路由,以便您可以$errors在每个请求中访问该变量。像这样:

Route::group(['middleware' => ['web']], function () {
    // Add your routes here
});

If you aren't going to build an API, another option is to move the "web" middlewares to the global middleware stack like in 5.1.

如果您不打算构建 API,另一种选择是像 5.1 一样将“web”中间件移动到全局中间件堆栈。

回答by Gowtham Selvaraj

Try using

尝试使用

return redirect()->back()
              ->withInput($request->all())
              ->withErrors($validator->errors()); // will return only the errors

回答by Marcin Nabia?ek

Try to replace:

尝试替换:

->withErrors($validator, 'error');

with:

和:

->withErrors($validator);

回答by Alex

// Replace

Route::group(['middleware' => ['web']], function () {
    // Add your routes here
});

// with 

Route::group(['middlewareGroups' => ['web']], function () {
    // Add your routes here
});

回答by Bindesh Pandya

I have my working validation code in laravel 5.2 like this

我在 Laravel 5.2 中有我的工作验证代码,如下所示

first of all create a function in model like this

首先在这样的模型中创建一个函数

In model add this line of code at starting

在模型中,在开始时添加这行代码

use Illuminate\Support\Facades\Validator;

使用 Illuminate\Support\Facades\Validator;

public static function validate($input) {

            $rules = array(
                'title' => 'required',
                'content.*.rate' => 'required',
              );
            return Validator::make($input, $rules);
        }

and in controller call this function to validate the input

并在控制器中调用此函数来验证输入

use Illuminate\Support\Facades\Redirect;

使用 Illuminate\Support\Facades\Redirect;

  $validate = ModelName::validate($inputs);
    if ($validate->passes()) {
          ///some code
     }else{
           return Redirect::to('Route/URL')
                            ->withErrors($validate)
                            ->withInput();
      }

Now here comes the template part

现在是模板部分

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

and Above all the things you must write your Route like this

最重要的是你必须像这样写你的路线

Route::group(['middleware' => ['web']], function () {

    Route::resource('RouteURL', 'ControllerName');
});

回答by Bashar

Wrap you Routes in webmiddleware like below:

将你的路由包裹在web中间件中,如下所示:

Route::group(['middleware' => ['web']], function () {
    // Add your routes here
});

and In app\Http\Kernel.phpmove \Illuminate\Session\Middleware\StartSession::classfrom the web$middlewareGroupsto $middleware

而在app\Http\Kernel.php移动\Illuminate\Session\Middleware\StartSession::classweb$middlewareGroups$middleware

Hope it will solve your problem.

希望它能解决你的问题。

回答by Bashar

This will work

这将工作

Route::group(['middlewareGroups' => ['web']], function () {
    // Add your routes here
});

as well as this also works

以及这也有效

Route::post('location',array(
    'as'=>'location',
    'middlewareGroups'=>'web',
    'uses'=>'myController@function'
));

回答by Eazy Sam

// Controller
$this->validateWith([
    'title' => 'required',
    'content.*.rate' => 'required',
]);


// Blade Template
@if ($errors->has('title'))
    <span class="error">
        <strong>{{ $errors->first('title') }}</strong>
    </span>
@endif
@if ($errors->has('anotherfied'))
    <span class="error">
        <strong>{{ $errors->first('anotherfied') }}</strong>
    </span>
@endif

Find the documentation.

查找文档

回答by Raheem Mohamed

Route

路线

Route::group(['middlewareGroups' => ['web']], function () {
    // Add your routes here
    Route::resource('/post', 'PostController');
});

Functions

职能

public function store(Request $request){
   $this->validate($request, [
       //input field names
      'title' => 'required|max:20',
      'body' => 'required',
   ]);
}

View

看法

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