0

I am trying to show any validation error in the blade file.

Below I have provided how my controller looks like :

$rules =array(
    'mobile' => 'required_without:landline',
    'landline' => 'required_without:mobile'
);
$validator = Validator::make($request->all(), $rules);
//process
if($validator->fails()){
    //$fieldsWithErrorMessagesArray = $validator->messages();
    //dd($fieldsWithErrorMessagesArray);

    return Redirect::back()->withErrors($errors)->withInput();
}

This is how my blade file looks like :

<?php
      echo print_r($errors,true);
?>

@if ($errors->has('mobile'))
     @foreach($errors->get('mobile') as $error)
             <span class="validation_error">{{$error}}</span>
     @endforeach
@endif

@if ($errors->has('landline'))
     @foreach($errors->get('landline') as $error)
             <span class="validation_error">{{$error}}</span>
     @endforeach
@endif

When the validation failed in the controlled, I had a 2 lines which I commented out (used for testing to see the error output).

This is what that dd($fieldsWithErrorMessagesArray); generated :

MessageBag {#218 ▼
  #messages: array:21 [▼
    "mobile" => array:1 [▼
      0 => "The mobile field is required when landline is not present."
    ],
    "landline" => array:1 [▼
      0 => "The landline field is required when mobile is not present."
    ]
  ]
}

However when I tried echoing out in the blade file, I am getting an empty array

This is how my kernel.php file looks like (located : 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,
];

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'ajaxOnly' => \App\Http\Middleware\OnlyAjax::class,
];

I am using Laravel 5.1. However I have also tried this on 5.8 and still getting the same issue. I am not sure why this is happening any help would be appreciated.

dark_illusion_909099
  • 1,067
  • 2
  • 21
  • 41

2 Answers2

0

In my case I solved it by removing \Illuminate\Session\Middleware\ StartSession::class from 'middleware' in Kernel.php, leaving it in the 'web' group in the same file.

The problem would be that the session only needs to be started only in the 'web' middleware group.

0

In my case I solved it by removing \Illuminate\Session\Middleware\ StartSession::class from 'middleware' in Kernel.php, it must be only in the 'web' group in the same file.