Clivern

A Software Engineer and Occasional Writer.

How To Validate Forms With Laravel Part2

22 March 2014

We discussed before how to create forms with laravel and then how to build validation rules. Now let’s see how to access error messages from form view.

We need to create simple form so create new file in app/views/ and name it form.blade.php then create two routes, One for form view and another for form submission. You can explore the following code.

<!--app/views/form.blade.php-->
<!doctype html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <title>
   Laravel
  </title>
 </head>
 <body>
  
  <!-- text input field -->
  
  
  <br/>
  <!-- email input -->
  
  
  <br/>
  <!-- submit buttons -->
  

  <!-- reset buttons -->
  

  
 </body>
</html>
Route::get('form', function(){
    //render app/views/form.blade.php
    return View::make('form');
});

Route::post('form-submit', function(){
    //get all inputs
    $inputs = Input::all();
    //create array of validation rules
    $rules = array(
        'username'=>'required|alpha_dash|min:4|max:35',
        'email'=>'required|email'
    );

    //validate inputs
    $validator = Validator::make($inputs,$rules);

    if($validator->passes()){
        //inputs valid
        echo 'Well';
    }else{
        //return to form view with errors
        return Redirect::to('form')->withErrors($validator);
    }
});

All error messages exist in $errors variable. You don’t have to check for its existance as it automatically added to our form view. As you can see i used withErrors() method to add form errors to errors object in form view. Here’s how to access errors in form view.

<!--app/views/form.blade.php-->
<!doctype html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <title>
   Laravel
  </title>
 </head>
 <body>
  
  <ul class="errors">
   @foreach($errors->all() as $error)
   <li></li>
   @endforeach
  </ul>
  <!-- text input field -->
  
  
  <br/>
  <!-- email input -->
  
  
  <br/>
  <!-- submit buttons -->
  

  <!-- reset buttons -->
  

  
 </body>
</html>

Go a head and visit http://localhost/<laravel dir>/public/form and submit form to check how errors shown.

We can use get() method to retrieve array of errors for single field. Here’s how to access email field errors and username field errors separately.

<!--app/views/form.blade.php-->
<!doctype html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <title>
   Laravel
  </title>
 </head>
 <body>
  

  <!-- text input field -->
  <ul class="errors">
   @foreach($errors->get('username') as $error)
   <li></li>
   @endforeach
  </ul>
  
  
  <br/>
  <!-- email input -->
  <ul class="errors">
   @foreach($errors->get('email') as $error)
   <li></li>
   @endforeach
  </ul>
  
  
  <br/>
  <!-- submit buttons -->
  

  <!-- reset buttons -->
  

  
 </body>
</html>

Go a head and visit http://localhost/<laravel dir>/public/form and submit form to check how errors shown.