February 2, 2015 11:53 am

Building A To Do List with Ajax Using Laravel 4 – Part 1

In this new tutorial series we will be using Laravel and jQuery to build a to-do list with Ajax. Through this application building we will learn how to use RESTFul controllers, RESTFul routing and Request types. We will be dividing this application development into different segments.

Building A To Do List with Ajax Using Laravel 4 - Part I

  • Creating and migrating our to do list’s database.
  • Creating a to do list model
  • Creating the template
  • Inserting data to the database with Ajax
  • Retrieving the list from the database
  • How to allow only Ajax requests

Let’s create a new project using below Artisan CLI command and Composer.

composer create-project laravel/laravel todolist

Let’s verify laravel installation by navigating to the Laravel project folder using browser. If you see laravel logo then it means laravel project creation successful.

laravel home page

Once laravel project creation successful we have to setup database configuration on app/config/database.php file against the database driver which we like to use. In this case we are going to use MySQL so our database configuration will look like following.

'mysql' => array(
			'driver'    => 'mysql',
			'host'      => 'localhost',
			'database'  => 'lucifier_todolist',
			'username'  => 'username',
			'password'  => 'password',
			'charset'   => 'utf8',
			'collation' => 'utf8_unicode_ci',
			'prefix'    => '',
		),

Creating and migrating our to do list’s database

Please check to previous tutorials to know more about migrations, how they are helpful to control development steps. To create our to do list migration, we have to use following Artisan CLI command:

php artisan migrate:make create_tasks_table --table=tasks --create

When we run this command, Artisan will generate a migration to generate a database table named tasks. Now we need edit this migration file for the necessary database table columns. We can find the migration file at app/database directory.

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateTasksTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('tasks', function(Blueprint $table)
		{
			$table->create();
			$table->increments("id");
			$table->string("title", 255);
			$table->enum('status', array('0', '1'))->default('0');
			$table->timestamps();
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::drop('tasks');
	}

}

To build a simple to do list, we need five columns:

  • The id column will store ID numbers of to do tasks
  • The title column will store a to do task title
  • The status column will store the status of each to do task
  • The created_at and updated_at columns will store the created and updated dates  of the to do tasks

If we use $table->timestamps() in the migration file, Laravel migration class automatically creates created_at  and updated_at columns. To apply migrations we have to use following command:

php artisan migrate

After running this command, we can see tasks table and columns have been created in our database. Now we have to write a model for this migration.

Creating a tasks model

To create a model, we should open a new file and save it in app/models/ directory with name task.php. We have to write the following code in this new model.

<?php
class Task extends Eloquent
{
	protected $table = 'tasks';
}

As we see our model, our Task class extends an Eloquent model, which is the ORM database class of Laravel. The protected $table = ‘tasks’; code tells Eloquent about our model’s table name. If we don’t set this table variable, Eloquent accepts the plural version of the lower case model name as the table name. Now our application needs a template file.

Creating the Template

Laravel uses a template engine called Blade for static and application template files. Laravel calls the template files from the app/views directory, so we need to create our first template under this directory and also named it as index.blade.php.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>To do List</title>

    <!-- Bootstrap -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">

  </head>
  <body>
    
    <div class="container">
  		<div class="row clearfix">
  			<div class="col-md-6 col-md-offset-3">
  				<h2 style="text-align:center;"> To do List </h2>  				

  			</div>
  		</div>
  	</div>

    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
  </body>
</html>

Our application will have below features based on that we will define our template code.

  • Adding a new Task
  • Updating the existing Task
  • Deleting the existing task
  • Updating the task status
  • Listing tasks

First we will see how we can add a task using Ajax. For adding a new task we need a form to handle task title as input. So let’s create a form.

<div class="panel panel-default">
              <div class="panel-heading">
                <h3 class="panel-title">
                  Add Task
                </h3>
              </div>
              <div class="panel-body">
                <form id="add_task" style="display:none;">
                    <input id="task_title" type="text" name="title" placeholder="Enter a task name" value=""/>
                    <button name="submit">Add Task</button>                      
                </form>
              </div>              
            </div>

In the above code we defined a form with id add_task and having an input variable called title to take care task title by user. At present we will be hiding this form because we will show this form when user wants to add a task only.

Once we add task using the above form we have to list them in a table so let’s create a table.

<div class="panel panel-default">
              <div class="panel-heading">
                <h3 class="panel-title" style="line-height:30px;">Tasks <div class="pull-right"><a href="#" onClick="show_form('add_task');" class="btn btn-info"><i class="icon-white icon-plus"></i> Add Task</a></div></h3>
              </div>
              <div class="panel-body">
                  @foreach($tasks as $task)
                    <table class="table" id="task_list">
                      <thead>                        
                        <tr>Title</tr>
                        <tr></tr>
                        <tr></tr>
                      </thead>
                      <tbody> 
                        @if($task->status)
                          <tr class="success" id="{{ $task->id }}">
                            <td id="title_{{ $task->id }}">{{ $task->title }}</td>
                            <td>Task Done</td>
                            <td><a href="#" onClick="delete_task('{{ $task->id }}');" class="btn btn-warning"><i class="icon-white icon-pencil"></i> Edit</a></td>
                            <td><a href="#" onClick="edit_task('{{ $task->id }}','{{ $task->title }}');" class="btn btn-danger"><i class="icon-white icon-remove"></i> Delete</a></td>
                          </tr>
                        @else
                          <tr id="{{ $task->id }}">
                            <td id="title_{{ $task->id }}">{{ $task->title }}</td>
                            <td><a href="#" onClick="task_done('{{ $task->id }}');" class="btn btn-info"><i class="icon-white icon-ok"></i> Task Done</a></td>
                            <td><a href="#" onClick="delete_task('{{ $task->id }}');" class="btn btn-warning"><i class="icon-white icon-pencil"></i> Edit</a></td>
                            <td><a href="#" onClick="edit_task('{{ $task->id }}','{{ $task->title }});" class="btn btn-danger"><i class="icon-white icon-remove"></i> Delete</a></td>
                          </tr>
                        @endif
                      </tbody>
                    </table>
                  @endforeach
              </div>
            </div>

In the above code we are giving a link to add task. When user clicks on add task link then we have to show the form. For this we are calling a function called show_form(‘add_task’); onclick of the link. So let’s write this javascript function in a new file in public/assets/js  directory and we will name this as script.js file.

function show_form(form_id)
{
	$('form').hide();
	$('#'+form_id).show('slow');
}

In the above function onclick of the link we are hiding all forms using javascript hide() method and then we are using form_id to show the add task form.

Let’s assume at present we get all the tasks from database in an array from controller called tasks, To list tasks we have to loop through the tasks array. While looping we are separating each task based on the task status. If the task status set to 1 then it is completed otherwise it’s incomplete. So we are providing task status update link to update task completion.

function task_done(id)
{
	$.get("/done/"+id, function(data){

		if(data == 'OK')
		{
			$('#'+id).addClass('success');
		}
	});
}

We are also providing options to edit and delete tasks. Let’s see those functions below.

function delete_task(id)
{
	$.get("/delete/"+id, function(data){

		if(data == 'OK')
		{
			var target = $('#'+id);
			target.hide('slow',function(){
				target.remove();
			});
		}
	});
}

function edi_task(id,title)
{
	$('#edi_task_id').val('id');

	$('#edi_task_title').val('title');

	show_form('edi_task');
}

Once user decided to add a task, he will see a add task form but what will happen when he submits with user input. At present we are not taking care of the add task and edit task functionalities by the user. So as per our application aims, we have to do these actions using Ajax. So let’s see how we can do these actions.

$('#add_task').submit(function(event){

	/* Stop form submitting normally */
	event.preventDefault();

	var title = $('#task_title').val();

	if(title)
	{
		//ajax post the form
		$.post('/add', {title:title}).done(function(data){

			$('#add_task').hide('slow');
			$('#task_list').append(data);
		});
	}else{
		alert("Please give a title to task");
	}

});

$('#edit_task').submit(function(event){

	/* Stop form submitting normally */
	event.preventDefault();

	var task_id = $('#edi_task_id').val();
	var title = $('#edit_task_title').val();
	var current_title = $('#title_'+task_id).text();
	var new_title = current_title.replace(current_title, title);

	if(title)
	{
		//ajax post the form
		$.post('/update/'+task_id, {title:title}).done(function(data){

			$('#edit_task').hide('slow');
			$('#title_'+task_id).text(new_title);
		});
	}else{
		alert("Please give a title to task");
	}

});

we will continue the next part of this tutorial in next post. In this tutorial we have built migrations, database schema design, created model to take care database queries and created the template also.

Thanks

Author Huzoor Bux

I am Huzoor Bux from Karachi (Pakistan). I have been working as a PHP Developer from last 5+ years, and its my passion to learn new things and implement them as a practice. Basically I am a PHP developer but now days exploring more in HTML5, CSS and jQuery libraries.


Tutorial Categories:

Leave a Reply

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