Undefined variable: errors in Laravel

2019-01-07 15:57发布

When I want to register a user in my laravel project, the page always says

Undefined variable: errors (View: /var/www/resources/views/auth/register.blade.php)"

According to the Laravel documentation, $errors should always automatically be set:

So, it is important to note that an $errors variable will always be available in all of your views on every request, allowing you to conveniently assume the $errors variable is always defined and can be safely used.

I have this on on every view when I use:

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

or any other way when I want to use the $errors variable.

Why is this? I never had this problem before.

Can someone help me please?

10条回答
Viruses.
2楼-- · 2019-01-07 15:59

Your problem will be fixed by using this method.

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

If this doesn't help you, just run the following artisan command in addition to the above code:

php artisan key:generate

I solved in this way while using 5.2.*

查看更多
你好瞎i
3楼-- · 2019-01-07 16:00

Also to be aware of: If you write tests and your view has $errors variable make sure you don't use WithoutMiddleware trait.

查看更多
趁早两清
4楼-- · 2019-01-07 16:00
protected $middleware = [              \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \Social\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \Social\Http\Middleware\VerifyCsrfToken::class,
];

/**
 * The application's route middleware groups.
 *
 * @var array
 */
protected $middlewareGroups = [
    'web' => [

    ],

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

/**
 * The application's route middleware.
 *
 * These middleware may be assigned to groups or used individually.

make your kernel look like this

查看更多
再贱就再见
5楼-- · 2019-01-07 16:03

I had this very same issue with Laravel 5.2.x.

Inside of the routes.php file try yo create your routes within the

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

statement.

查看更多
劫难
6楼-- · 2019-01-07 16:14

Go to App\Http\Kernel.php file. Move all the things of $middlewareGroups properties to $middleware.

Check for more details- http://www.tisuchi.com/laravel-5-2-undefined-variable-error-validation/

查看更多
爱情/是我丢掉的垃圾
7楼-- · 2019-01-07 16:17

I was seeing this error too and later realised I had used the WithoutMiddleware trait as a means to bypass authentication for this particular test, but it ended up removing the validation error binding too. So I had to stop using the trait to keep the views working.

查看更多
登录 后发表回答