X
    Categories: Database Tutorials, Tips and GuidesLearn Laravel Tutorials, Tips And GuidesLearn PHP Tutorials, Tips And Guides

Creating ToDo Application in Laravel 5.4: Migrating Table, Creating Controllers & Models

Note: This series assumes that you have working knowledge of MVC and how Laravel implements this concept. If you want to speed up with this topic, check out my series on MVC in Laravel starting from installing Laravel 5.4.

In this series, I am going to build upon my previous Laravel series and create a complete application using Laravel 5.4. In this application, I am going to cover various Laravel concepts including Migrations, Authentication, FileSystem and Eloquent ORM.

What Am I Going To Create?

The ToDo application will have the following functionalities:

  • User Authentication with login and registration
  • Only authenticated user can perform ToDo CRUD actions

Let’s get started with creating a new Laravel application with the name todoapp.

Create the Laravel Project

To create a new Laravel project with the name todoapp, run the following command:

composer create-project laravel/laravel todoapp

Create the Database

Next, I will create a database with the name todoapp on the server .

With the database now created, I will next configure the .env file for database.

Open the project folder and then the .env file in the editor. Add the database setup information in the file:

DB_CONNECTION=mysql

DB_HOST=127.0.0.1

DB_PORT=3306

DB_DATABASE=todoapp

DB_USERNAME=root

DB_PASSWORD=

The database is now ready for use. Next, I will create migration tables, and then migrate them.

Create Tables for Migration

Two migration tables (one for Users and the other for Password_resets) come preinstalled with the default Laravel installation. I am going to modify the Users table and create a new migration table Todo.

Let’s first modify the Users table. Open the file 2014_10_12_000000_create_users_table.php located in the database/migrations folder. At the moment, the `up()` method in this file looks like:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password',255);
        $table->rememberToken();
        $table->timestamps();
    });
}

Let’s now add some more fields in it. One for the userimage and the second for its API key.

Before going further, let’s first understand what the two methods (`up()` and `down()`) do in the migration file. In the `up()`, I will define the schema for the table, add new columns, etc. In the `down()`, I will do the reverse such as dropping the table or reverse our previous changes.

I will now modify `up()` method:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->string('userimage');
        $table->string('api_key')->nullable()->unique();
        $table->rememberToken();
        $table->timestamps();
    });
}

Now that the table for the users is completed, I will create a new migration table for Todo. For that, run the following command on the command line inside the todoapp folder.

php artisan make:migration create_todo_table

Once the command finishes, a new migration file will be created. I will next create the table schema in the `up()` method of this file.

public function up()
{
    Schema::create('todo', function (Blueprint $table) {
        $table->increments('id');
        $table->string('todo');
        $table->string('description');
        $table->string('category');
        $table->integer('user_id')->unsigned();
        $table->timestamps();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    });
}

In the todo table, I have created a primary key, a todo column and a description column. I have also created a category column for todo category and created a foreign key on `user_id` which matches the `id` of a `user` in the `users` table. Finally, I created  two timestamps columns  using the `timestamps()` method. These two columns will be updated automatically by Laravel whenever a todo is inserted or updated.

Migrating Tables Using Artisan

Now that I have created all the required migration for tables, I will execute the migration with a single command:

php artisan migrate

Once the command is completed, all the tables will be created in the database:

Note:

If the commands fails and you get a Specified key was too long error, chances are that you are using a MySQL version older than 5.7. In this case, you need to define default string length in the AppServiceProvider.php file (located inside the app/Providers folder). Open the file and add the following line before the start of the class.

use Illuminate\Support\Facades\Schema;

And, in the `boot()` method (in the class), add the following line of code:

Schema::defaultStringLength(191);

Now, try re-running the command. It will work with a hitch. For more information, refer to laravel-news.com

Create Models and Controllers

Now I have the tables in the database. Next, I will create models for the tables. Model for the Users table comes with the default Laravel installation. The model and the controller for the todo table will be created with a single command:

php artisan make:controller TodoController --resource --model=Todo

When the above mentioned command is executed, the command you will ask to generate the Todo model since its not exists at the moment. Once you type yes, it will generate the model and then bind it with the controller.

Once the command finishes, the controller and the model for the app are ready for use.

Modifying the Models

Todo Model

Let’s start with adding fillable columns in the Todo model. For this, open Todo.php file (found inside the app folder). Add the following line inside the class.

protected $table = 'todo';

protected $fillable = ['todo','category','user_id','description'];

At this point, the Todo model will look like this:

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Todo extends Model
{
    protected $table = 'todo';
    protected $fillable = ['todo','category','user_id','description'];
}

User Model

Next, I will edit the Users model and add the user_image column in its fillable.  In addition, I will also define its relation with the Todo model. Open the User.php file and make the following changes:

  • First, add `user_image` inside the `$fillable` array.
  • Second, create a new public `todo()` method which will create one-to-many relationships with the todo table.
    public function todo()
    {
         return $this->hasMany('App\Todo');
    }

    `hasMany()` method defines the one-many relationship in Eloquent.

At this point, the new User.php file will look like:

<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
    use Notifiable;
    /**
    * The attributes that are mass assignable.
    *
    * @var array
    */
    protected $fillable = [
        'name', 'email', 'password','userimage'
    ];
    /**
    * The attributes that should be hidden for arrays.
    *
    * @var array
    */
    protected $hidden = [
        'password', 'remember_token',
    ];
    /*
    * Get Todo of User
    *
    */
    public function todo()
    {
        return $this->hasMany('App\Todo');
    }
}

Summarizing Part 1

In this part, I created a new Laravel project, complete with the database, migration table for todo and modified users migration table. Next, I migrated all the tables in a database using Artisan command. Then I created and modified the associated controllers and models.

What I Am Going to Discuss in the Next Part?

In the next part, I am going to create authentication for the users using Artisan and modify it to the purposes of the todo app. I will also modify the `TodoController` and set it up to perform CRUD. I will also create views to view, add and edit todo items. Stay tuned for the next part and if you have questions, do feel free to add comments below.

Ahmed Khan: Ahmed was a PHP community expert at Cloudways - A Managed PHP Hosting Cloud Platform. He is a software engineer with extensive knowledge in PHP and SEO. He loves watching Game of Thrones is his free time. Follow Ahmed on Twitter to stay updated with his works. You can email him at ahmed.khan@cloudways.com