php Laravel 5.2 $errors 没有出现在 Blade 中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34438463/
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-08-25 23:59:10  来源:igfitidea点击:

Laravel 5.2 $errors not appearing in Blade

phplaravellaravel-5.2

提问by Neal Crowley

So I'm following along with the Laravel 5 fundamentals tutorial and I am stuck on the form validation. I have followed along exactly with the tutorial but I am getting a Undefined variable: errors in my create articles view.

所以我跟着 Laravel 5 基础教程,我被困在表单验证上。我完全按照教程进行了操作,但我收到了一个未定义的变量:在我的创建文章视图中出现错误。

In the tutorial I am following and what I have found online they say the errors variable is always there in the blade file for you to use so I don't know what i am doing wrong?

在我正在关注的教程中以及我在网上找到的内容中,他们说刀片文件中始终存在错误变量供您使用,所以我不知道我做错了什么?

Any help would be appreciated! loving Laravel except for this error!

任何帮助,将不胜感激!喜欢 Laravel,除了这个错误!

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

Controller

控制器

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;
use App\Http\Requests;
use App\Http\Requests\UserRequest as UserRequest;
// use App\Http\Requests\CreateArticleRequest as CreateArticleRequest;
use App\Http\Controllers\Controller;
use Illuminate\View\Middleware\ErrorBinder;

class UserController extends Controller
{
    public function create(){
      return view('pages.signUp');
    }

    public function store(UserRequest $request){
      User::create($request->all());
      return 'the user has been registered!';
      return view('user.profile');
    }

}

Request validation

请求验证

<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;

class UserRequest extends Request
{
    /**
     * 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',
            'email' => 'required|email',
            'country' => 'required',
            'password' => 'required|min:6',
            'confirm_password' => 'required|same:password',
            'height' => 'required',
            'weight' => 'required',
        ];
    }
}

回答by user1669496

This is a breaking problem with the 5.2 upgrade. What's happening is the middleware which is responsible for making that errorsvariable available to all your views is not being utilized because it was moved from the global middleware to the webmiddleware group.

这是 5.2 升级的一个重大问题。发生的事情是负责使该errors变量可用于所有视图的web中间件未被使用,因为它已从全局中间件移至中间件组。

There are two ways to fix this:

有两种方法可以解决这个问题:

  1. In your kernel.phpfile, you can move the middleware \Illuminate\View\Middleware\ShareErrorsFromSession::classback to the protected $middlewareproperty.

  2. You can wrap all your web routes with a route group and apply the webmiddleware to them.

    Route::group(['middleware' => 'web'], function() {
        // Place all your web routes here...
    });
    
  1. 在您的kernel.php文件中,您可以将中间件\Illuminate\View\Middleware\ShareErrorsFromSession::class移回protected $middleware属性。

  2. 您可以使用路由组包装所有 Web 路由并将web中间件应用于它们。

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

回答by Md. Khairullah Nayan

Solved

解决了

You may change any one of the following:

您可以更改以下任何一项:

1. put your working route (app/http/routes.php)on

1.把你的工作路线(app/http/routes.php)放在

Route::group(['middleware' => ['web']], function () { // Here like Route::get('/', 'TodoController@index'); Route::post('/', 'TodoController@store'); });

Route::group(['middleware' => ['web']], function () { // Here like Route::get('/', 'TodoController@index'); Route::post('/', 'TodoController@store'); });

Screenshot -

截屏 -

Screendshot 1

截图 1

2. Move your protected $middlewareGroups web(app/Http/Kernel.php)on protected $middleware = []

2.将您的protected $middlewareGroups web(app/Http/Kernel.php)protected $middleware = []

Screenshot -

截屏 -

screenshot2

截图2

回答by Yuri

This is solution:

这是解决方案:

Change the defination of your Route groups with a middleware, from:

使用中间件更改路由组的定义,

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

to

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

Source: https://github.com/laravel/framework/issues/13000

来源:https: //github.com/laravel/framework/issues/13000

回答by Mohamed Radhi Guennichi

simply, you have to move :

简单地说,你必须移动:

\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,

from protected $middlewareGroupsto protected $middleware

protected $middlewareGroupsprotected $middleware

回答by Atiqur

  1. Just remove , 'middleware' => 'web'from Route::group(array('prefix' => 'user', 'middleware' => 'web'), function()in routes.phppage OR

  2. Move

    \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class,

  1. 只是删除, 'middleware' => 'web'Route::group(array('prefix' => 'user', 'middleware' => 'web'), function()routes.php文件页面或

  2. 移动

    \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class,

From protected $middlewareGroupsto protected $middlewarein kernel.phppage

protected $middlewareGroupsprotected $middlewarekernel.php页面

As the Laravel Documentation says:

正如 Laravel 文档所说:

Note: If your copy of Laravel has a RouteServiceProvider that already includes the default routes file within the web middleware group, you do not need to manually add the group to your routes.php file.

注意:如果你的 Laravel 副本有一个 RouteServiceProvider 已经包含 web 中间件组中的默认路由文件,你不需要手动将该组添加到你的 routes.php 文件中。

So removing from routes.phpfile would be the correct way.

所以从routes.php文件中删除将是正确的方法。

回答by Sambhav Pandey

Posting this as it might be useful for others,

发布此信息,因为它可能对其他人有用,

As Smartrahat mentioned in 1st solution, in your Kernel.phpfile(app/Http/Kernel.php) move \Illuminate\View\Middleware\ShareErrorsFromSession::classfrom $middlewareGroupsto protected $middlewareproperty, but the same will start throwing the error "Session store not set on request",

正如 Smartrahat 在第一个解决方案中提到的,在您的Kernel.phpfile( app/Http/Kernel.php) 中\Illuminate\View\Middleware\ShareErrorsFromSession::class$middlewareGroupstoprotected $middleware属性移动,但同样会开始抛出错误“会话存储未按请求设置”,

to resolve this move \Illuminate\Session\Middleware\StartSession::class,to $middleware propertyas well.

要解决这一举动 \Illuminate\Session\Middleware\StartSession::class,$middleware property为好。

回答by agent47

A couple of observations regarding this issue. First off there a related bug in github regarding this issue PFA https://github.com/laravel/framework/issues/12022

关于这个问题的一些观察。首先在 github 中有一个相关的错误关于这个问题 PFA https://github.com/laravel/framework/issues/12022

If you look at the last comment which Graham wrote, I think that is the facing I was facing. For me even though there was a error in form post data, I was getting the below equality

如果你看一下格雷厄姆写的最后一条评论,我认为这就是我所面对的。对我来说,即使表单发布数据有错误,我也得到了以下等式

boolval(count($errors) === 0) === true

In my case I added log statements in the

在我的情况下,我在

\Illuminate\Session\Middleware\StartSession::class

the above middleware class ran twice for a given request, I am not sure why it ran twice, but I think because of this the $errorsvariable is getting reset. I was using this configuration (which I think came default with [email protected])

上面的中间件类针对给定的请求运行了两次,我不确定为什么它运行了两次,但我认为因此$errors变量正在重置。我正在使用这个配置(我认为这是 [email protected] 的默认配置)

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',
    ],
];

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];

I changed the configuration which worked for me and the $errorsvariable's count is not zero (also the above middleware ran only once per request)

我更改了对我有用的配置,$errors变量的计数不为零(上述中间件每个请求只运行一次)

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

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

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

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];

Note: All my routes are in the webmiddleware group before and after the Kernel.php configuration change, I didnot move my routes at all from the webmiddleware group.

注意:我所有的路由在webKernel.php 配置更改前后都在中间件组中,我根本没有从web中间件组中移动我的路由。

回答by Dan Dart

As of 5.2, routes.phpis by default already called in the context of a ['middleware'=>'web']by RouteServiceProvider. But in routes.phpdefault generation of auth routes, the Route::groupcall is still happening by default - so if you delete that Route::groupdeclaration from routes.phpthe application then correctly shows errors.

从 5.2 开始,routes.php默认情况下已经在['middleware'=>'web']by的上下文中调用RouteServiceProvider。但是在routes.phpauth 路由的默认生成中,Route::group调用仍在默认情况下发生 - 因此,如果您Route::grouproutes.php应用程序中删除该声明,则会正确显示错误。

回答by smartrahat

Change @foreach($errors->any() as $error)to @foreach($errors->all() as $error)

更改@foreach($errors->any() as $error)@foreach($errors->all() as $error)

回答by JDA3

Having both Web and API requirements in our application, we did not want to move the middleware around; perhaps that would have worked, however:

在我们的应用程序中同时满足 Web 和 API 要求,我们不想移动中间件;然而,也许这会奏效:

We had the very peculiar situation that the flash[]and $errorssession data was transmitted correctly between the standard laravel resource methods, store()and edit(), but in some cases the data did not get back across nearly identical methods, storeSale()and editSale().

我们遇到了非常特殊的情况,即flash[]$errors会话数据在标准 Laravel 资源方法store()和之间正确传输edit(),但在某些情况下,数据没有通过几乎相同的方法返回,storeSale()并且editSale()

We found that in our development and deployment environments, the 'file' and 'database' session drivers worked in all cases, but the 'cookie' driver did not.

我们发现在我们的开发和部署环境中,“文件”和“数据库”会话驱动程序在所有情况下都有效,但“cookie”驱动程序却没有。

Switching to the database driver in all instances solved the problem.

在所有情况下切换到数据库驱动程序解决了这个问题。