2

I am using laravel 5.1 and flash messages. I want to show a flash message to the user when the validator fails.

My code looks like this:

/* 
    Validation
*/

$rules = array(
    'username'  => 'alpha_numeric_spaces|required|min:3|max:12|not_in:edit,password|unique:users,username', 
    'email'     => 'email|unique:users,email', 
    'password'  => 'required|min:6|confirmed',
    'rules'     => 'required|'

);

$validator = Validator::make(Input::all(), $rules);

if ($validator->fails()) {
    flash()->error($validator->messages());
    return redirect()->back()->withInput();
}

But I'm getting errors in flash message with bad text:

{
    "username": ["The username has already been taken."],
    "email": ["The email has already been taken."]
}

My problem is: I'm getting bad format messages.

"username": ["The username has already been taken."],

instead of

The username has already been taken.

Problem image: HERE

Tommy
  • 23
  • 4

1 Answers1

1

Try to use Session::flash in your controller:

Session::flash('error', $validator->messages());

And Session::get() in your blade template:

@if (Session::has('error'))
    <div class="alert alert-warning" align="center">{{ Session::get('error') }}</div>
@endif 

This should work, but if you still get the exact same error, try to iterate:

@foreach (Session::get('error') as $er => $errorMessage )
    {{ $errorMessage[0] }}
@endforeach
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
  • 1
    Thanks for answering. The problem is that I'm getting bad format messages ""username": ["The username has already been taken."]," instead of "The username has already been taken". – Tommy Mar 07 '16 at 08:44
  • If you're getting the same object as in your post, added code should work. Please try my code and tell me if it works or not. – Alexey Mezenin Mar 07 '16 at 08:51
  • 1
    You can't get same message if you use `Session::` in controller and `@foreach` code in the view. You'll see another kind of error (because of wrong iteration logic) or it'll work, but you'll never get `{ "username": ["The username has already been taken."], "email": ["The email has already been taken."] }` – Alexey Mezenin Mar 07 '16 at 09:55