Laravel 4 offers some great helper classes and methods for validating user input. We’ll take quick look at some of them in this article.
Assumptions:
- You have some routing setup to accept POST requests
- You have a controller to handle the POST request
Here’s the skeleton for our controller (our routing points to @registerUser
):
class UsersController extends BaseController { public function registerUser() {} }
I also have an array of rules inside my corresponding model (User.php
– the one you get for free from Laravel). This could be an array from anywhere, you just need to reference it later on:
/** * Registration form validation rules */ public static $registrationRules = array( 'email' => 'required|email|unique:users', 'password' => 'required|between:6,18|confirmed', 'password_confirmation' => 'required' );
The confirmation validation works by suffixing the original field with _confirmation
. As you can see – password becomes password_confirmation. Laravel then understands the association. There are many more rules you can include, but I only needed a few for this example.
Then back inside our UsersController.php
, we can add our validation rules to the user input:
class UsersController extends BaseController { public function registerUser() { $validator = Validator::make( Input::all(), User::$registrationRules ); // 1 if( $validator->passes() ) { // 2 $user = new User; $user->email = Input::get( 'email' ); $user->password = Hash::make( Input::get( 'password' ) ); $user->save(); } else { return Response::json( array( 'error' => true, 'msg' => $validator->messages() // 3 ), 400 ); } } }
- We create a new instance of
Validator
and pass in all the user input and run it by our validation rules (which is an array inside of ourUser.php
model. - If it validates, we process the user details and add it into the database
- If the user input doesn’t validate, we pass the automatically generated error messages back as JSON as a 400 response to the client
These great validation helper methods really speed up your development time.