Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to access validation errors in view

I have set up a controller with some validation.

public function attemptLogin()
{
    $rules = array(
        'email'=>'required|email', 
        'password'=>'required'
    );


    $validator = Validator::make(Input::all() , $rules);
    if($validator->fails()){
        return Redirect::to('login')->withErrors($validator);
    };
}

If I output the messages directly in the controller

$messages = $validator->messages();
print_R($messages->all());

I get the validation errors - however if I redirect:

return Redirect::to('login')->withErrors($validator);

The $errors array available in the view is always coming up empty.

like image 755
PokeItWithAStick Avatar asked Jan 21 '13 12:01

PokeItWithAStick


2 Answers

From laravel four documentation

Note that when validation fails, we pass the Validator instance to the Redirect using the withErrors method. This method will flash the error messages to the session so that they are available on the next request.

Variable $errors it's not an array.

The $errors variable will be an instance of MessageBag.

For some reason I don't really like @seamlss idea. You can use this instead.

@if(Session::has('errors'))
<? $errors = Session::get('errors'); ?>
<div class="alert alert-error">
    <button type="button" class="close" data-dismiss="alert">&times;</button>
    <ul>
        <li id="form-errors" >
            <h3> {{ $errors->first('email') }}</h3>
        </li>
    </ul>
</div>
@endif

I've used some bootstrap components, don't get confused, the only thing you need is the lines with the curly braces and the magical @ sign.

From laravel docs error-messages-and-views

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.

You can also check this

@if( $errors->has('email') )
    <div class="control-group error">
        <label class="control-label" for="email">Email</label>
        <div class="controls">
            <input type="text" id="email" placeholder="Email" name="email">
            <span class="help-inline">{{ $errors->first('email') }}</span>
        </div>
    </div>
@endif
like image 147
13 revs, 2 users 99% Avatar answered Oct 17 '22 13:10

13 revs, 2 users 99%


I've had success redirecting using ->withErrors($validation)

And then in the view checking the condition @if( $errors->count() > 0 )...

@if( $errors->count() > 0 )
    <p>The following errors have occurred:</p>

    <ul id="form-errors">
        {{ $errors->first('username', '<li>:message</li>') }}
        {{ $errors->first('password', '<li>:message</li>') }}
        {{ $errors->first('password_confirmation', '<li>:message</li>') }}
    </ul>   
@endif
like image 26
seamlss Avatar answered Oct 17 '22 12:10

seamlss