Using automatic validation in laravel models

When validating data that’s being sent to the database, ideally we should put the rules and
validation in our model. In this recipe we’ll see one way to accomplish this.

Getting ready

For this recipe, we need a standard Laravel installation with a configured MySQL database.
We also need our migrations table set up by running the Artisan command php artisan

How to do it…

To complete this recipe, follow these steps:
1. In the command prompt, create a migration for a simple users table:
php artisan migrate:make create_users_table
2. Create the schema in the migration file. The file is located in the app/database/
migrations directory and will be named something like 2012_01_01_222551_
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration {
* Make changes to the database.
* @return void
public function up()
Schema::create(‘users’, function($table)
$table->string(‘username’, 100);
$table->string(’email’, 100);

* Revert the changes to the database.
* @return void
public function down()

3. Run the migration:
php artisan migrate
4. Create a file named User.php in our app/models directory. If there’s already a file
named User.php, we can just rename it:
class User extends Eloquent {
protected $table = ‘users’;
private $rules = array(
’email’ => ‘required|email’,
‘username’ => ‘required|min:6′
public function validate($input) {
return Validator::make($input, $this->rules);

5. Make a route that loads the ORM and tries to save some data:
$user = new User();
$input = array();
$input[’email’] = ‘’;
$input[‘username’] = ‘Short’;
$valid = $user->validate($input);
if ($valid->passes()) {
echo ‘Everything is Valid!’;
// Save to the database
} else {

How it works…

To begin, we create a migration for a basic users table. In our schema, we set up a table
with an ID, username, e-mail ID, and timestamps. Then run the migration to create the table
in the database.
Next, we set up our User model and extend Eloquent. We need to create our rules, using a
private variable named as $rules that contains an array of the validation rules we want to
check. In our model, we create a validate method. This will run our input through Laravel’s
Validator using the rules we have just set up.

Leave a Reply

Your email address will not be published. Required fields are marked *