4

I am trying to display validation errors when going back to a View, in Laravel 5.2. The $errors variable is empty and in a similar question Laravel 5.2 $errors not appearing in Blade it has been proposed to:

(1) move the ShareErrorsFromSession middleware to the $middleware property

or

(2) wrap the relevant route with web middleware.

Of course, solution 1 (which works) is not applicable in my case because I have some API routes, as it is well stated in Laravel 5.2 validation errors.

To be more specific, I am using multiple authentication guard drivers and routes that use token authentication are stateless. So what us left is solution 2. It should work, but it doesn't work (OR I am missing something). No matter if I place my routes (the ones in which I want to display validation errors) inside the group:

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

or just inside:

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

the $errors variable seems empty. Dumping the variable gives:

object(Illuminate\Support\ViewErrorBag)#209 (1) {
  ["bags":protected]=>
  array(0) {
  }
}

The web group is typically defined in kernel.php as:

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

My controller looks like:

$form = Input::all();   
$rules = Config::get('validation.contact');            
$validation = Validator::make($form,$rules);

if ($validation->fails()){             
    return Redirect::back()->withErrors($validation);
} else {
    ...
}

Any ideas?

UPDATE (after answered):

You were right Alexander! I missed that recent change. But what about API routes that need not invoke these middlewares? Should we revert this change as described in Web middleware being applied to API routes in Laravel 5.2 ? If yes, then maybe it is better to strip middlewares from web group and put them in a new group (e.g myweb). This way we are not messing with the framework.

Community
  • 1
  • 1

1 Answers1

1

If you are running Laravel 5.2.27 and later, you don't need to include "web" middleware in your routes. Because, starting from the mentioned version, it is already implicitly included by default. In fact, re-including that middleware can cause some odd issues. Source: Validation error in Laravel - $errors array does not get populated after the validation failure

Community
  • 1
  • 1
Alex Lomia
  • 6,705
  • 12
  • 53
  • 87