# Laravel Tutorial: Todo model

Generate a Todo Model + Migration

Since we will be creating a Todo list application, let us first define the Todo schema:

Todo {
  id: Integer,
  todo: String,
  completed: Boolean
}

To generate the Todo model and it's corresponding database migration run the following command:

$ php artisan make:model Todo --migration

You should see an output similar to the following:

Model created successfully.
Created Migration: yyyy_mm_dd_123456_create_todos_table

Open the migration file (found in laravel-todolist/database/migrations/yyyy_mm_dd_123456_create_todos_table) in your favorite text editor and modify the Schema::create('todos', ...) block to look like this:


// ....skipping few lines....
Schema::create('todos', function (Blueprint $table) {
    $table->increments('id');

    $table->longText('todo');
    $table->boolean('completed');

    $table->timestamps();
});
// ....skipping few lines....

We have defined the schema for our todos table, with todo being a long string of text and completed being of boolean type.

Now that we have defined the schema for our todos table, let us write some validation rules for our newly created Todo model.

Open the Todo model file (found in laravel-todolist/app/Todo.php) and modify the file as shown below (changes are highlighted):


<?php

namespace App;

use Validator;
use Illuminate\Database\Eloquent\Model;

class Todo extends Model
{
  private $errors;

  private $rules = array(
    'todo' => 'required',
    'completed' => 'required'
  );

  protected $fillable = array('todo', 'completed');

  public function validate($data)
  {
    $v = Validator::make($data, $this->rules);

    if ($v->fails())
    {
        $this->errors = $v->errors();
        return false;
    }

    return true;
  }

  public function errors()
  {
      return $this->errors;
  }
}

We first ensure that todo and completed are the only parameters fillable when mass assigned (Read more about mass assignment here: https://laravel.com/docs/5.1/eloquent#mass-assignment). Then we define a validate function that takes the parameter $data as an argument and checks to see if the parameters received adhere to the rules defined. If not the error is stored in a variable. This is all there is to our simple Todo model. Next we will create a controller to interface between our Model and the View.