Create Todo App with CodeIgniter 3 + AngularJs

CodeIgniter Logo

3. Create a restful controller

I created a controller named API with methods for create, read, update, and delete (CRUD). The controller need to extends Rest_Controller. The breakdown of  API controller as follows:

(i) Extending the Rest_Controller

require APPPATH.'/libraries/REST_Controller.php';

class Api extends REST_Controller
{
.
.

(ii) Create a GET method to fetch all tasks. The method also will return a specific task if parameter ID is supplied.

public function tasks_get()
{
	if(! $this->get('id'))
	{
		$tasks = $this->task_model->get_all(); // return all record
	} else {
		$tasks = $this->task_model->get_task($this->get('id')); // return a record based on id
	}

	if($tasks)
	{
		$this->response($tasks, 200); // return success code if record exist
	} else {
		$this->response([], 404); // return empty
	}
}

(iii) Create a POST method to insert new task into database.

public function tasks_post()
{
	if(! $this->post('title'))
	{
		$this->response(array('error' => 'Missing post data: title'), 400);
	}
	else{
		$data = array(
			'title' => $this->post('title')
		);
	}
	$this->db->insert('task',$data);
	if($this->db->insert_id() > 0)
	{
		$message = array('id' => $this->db->insert_id(), 'title' => $this->post('title'));
		$this->response($message, 200);
	}
}

You can put more extensive validation by using CodeIgniter Form Validation library.