phpvalidationlaravellaravel-4

Looping through validation errors in view


I'm using Laravel's form validation functionality and trying to work out how I can loop through the form errors in my view. At the moment, I'm successfully validating the form using the below code:

public function create()
{
    $validator = Validator::make(
        Input::all(),
        array(
            'username' => 'required|alpha_num|unique:users',
            'email' => 'email|unique:users',
            'password' => 'required|min:6',
            'passwordConf' => 'required|same:password'
        )
    );

    if ($validator->fails())
    {
        return Redirect::to('join')->withErrors($validator);
    }

    return View::make('user/join')->with();
}

The validator successfully validates the form and redirects to the join route if validation fails. Obviously, I'd also like to show the validation messages to the user. I have a master.blade.php layout file which all of my views extend, and in the layout I have the following code:

@if (Session::has('errors'))
    <div class="alert alert-danger">
        @foreach (Session::get('errors') as $error)
            Test<br />
        @endforeach
    </div>
@endif

This seems to half work. If there are validation errors, the alert div does show on the page, however no validation errors get output. That suggests that Session::has('errors') is returning true however I'm obviously not iterating through the validation errors correctly.

How do I iterate through the validation errors sent to the view via withErrors?


Solution

  • There's an automatic $errors variable passed to your view. You don't have to check the session directly.

    @foreach ($errors->all() as $error)
        {{ $error }}<br/>
    @endforeach
    

    Here's a quote from the docs:

    Notice that we do not have to explicitly bind the error messages to the view in our GET route. This is because Laravel will always check for errors in the session data, and automatically bind them to the view if they are available. 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. The $errors variable will be an instance of MessageBag.