The problem is that withErrors() is working perfectly in this code, but withMessage() isn't.
I also tried with('message', 'Test message!'). In views file, I can retrieve withErrors using $errors variable, but if I want to retrieve withMessage, I have to use Session::get('message'). Why is $message not working?
Controller:
public function registration() {
$rules = array(...);
$validator = Validator::make(Input::all(), $rules);
if($validator->fails()) {
return Redirect::route('registration')->withErrors($validator);
}
else {
//Some code here...
return Redirect::route('registration')->withMessage('Test message!');
}
}
Template:
@extends('default.base')
@section('main')
@if(!empty($errors->all()))
<div class="alert alert-danger" role="alert">
<ul>
@foreach($errors->all() as $error)
<li>{{ $error }}
@endforeach
</ul>
</div>
@endif
@if(isset($message))
{{ $message }}
@endif
@stop
That is because errors
is a special case. When creating a view, Laravel check's if there is a session variable with the name errors
. If so it will then pass the contents as $errors
to the view.
Illuminate\View\ViewServiceProvider@registerSessionBinder
if ($me->sessionHasErrors($app))
{
$errors = $app['session.store']->get('errors');
$app['view']->share('errors', $errors);
}
This means you either use Session::has('message')
and Session::get('message')
in your view or you add a View Composer that does basically the same that Laravel does with errors
:
View::composer('*', function($view){
if(Session::has('message')){
$view->with('message', Session::get('message'));
}
});