Building RESTful API in Laravel – part 2 – Design API Controller

In the previous tutorial (https://maxoffsky.com/code-blog/building-restful-api-in-laravel-start-here/) I shared the basics of RESTful controller structure and a route that we will need to build a RESTful web application. As promised, in this tutorial we will explore how exactly to make our API work with our data.

We will explore a simple Todo list application as and example.

Let’s start with a simple structure for the Todo database. I am using MySQL but you can use whatever DB you are comfortable with, just make sure Laravel supports it.

Our Todo items will have id, title (name of the todo), completed (yes or no) and timestamps.

Create a new DB called “apitest” and run this SQL query to create necessary fields :

CREATE TABLE `todos` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `completed` varchar(4) NOT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Make sure you update your application/config/database.php file with the name of your DB and credentials.

Alright, we have a clean DB, now let’s make a Laravel model so that it’s aware of DB structure.

Create a file called todo.php in your application/models. Copy/paste the following :

<?php

   class Todo extends Eloquent {

   }

?>

That’s it for the model!

Let’s go back to our controller structure from the previous tutorial and fill it up with meaningful actions on the model.

Before that, let’s think about it for a minute, what should we be able to do with our data?

We need to receive our data about a todo as a JSON string of data, for example like this :

{"id":"1","title":"First todo","completed":"no","created_at":"2012-11-16 22:22:53","updated_at":"2012-11-16 22:23:07"}

Laravel has amazing Eloquent methods of working with data, and we will be using some of that potential to make our app do what we want it to do. There is one feature of Laravel that people sometimes miss, Returning Eloquent models as JSON responses, as documented in the docs: http://laravel.com/docs/views.

This means we could do something like this in our controller :

return Response::eloquent(Todo::find(1));

And we will get exactly what we want – a Todo item with id 1, that will look like the one JSON string above.

Awesome, isn’t it?

Let’s sketch the algorithm and flow of our application, analyzing each action in enough detail to get a vision of our TODO API:

GET index (ID) should return all Todos in JSON encoded format if there is no ID present, otherwise return JSON encoded object of the todo with ID.

POST index should get our JSON input and create a new todo and save it to the database. We can return the JSON-inified new todo back to our application to acknowledge creation of new object.

PUT index should receive input that contains an ID, “title” and “completed” data, then check if the todo with ID exists, then updated that todo with the new data.

DELETE index (ID) should receive ID as a parameter, find a todo with that ID and delete it if it exists, otherwise return an error.

Simple enough? Let’s code our controller right away then!

<?php

class Api_Todos_Controller extends Base_Controller {

	public $restful = true;

	public function get_index($id = null) 
	{
		if (is_null($id )) 
		{
			return Response::eloquent(Todo::all());
		} 
		else 
		{
			$todo = Todo::find($id);

			if(is_null($todo)){
			    return Response::json('Todo not found', 404);
			} else {
	        	    return Response::eloquent($todo);
			}
		}
	}

	public function post_index() 
	{

		$newtodo = Input::json();

		$todo = new Todo();
		$todo->title = $newtodo->title;
		$todo->completed = $newtodo->completed;
		$todo->save();

		return Response::eloquent($todo);
	}

	public function put_index() 
	{
		$updatetodo = Input::json();

		$todo = Todo::find($updatetodo->id);
		if(is_null($todo)){
		    return Response::json('Todo not found', 404);
		}
		$todo->title = $updatetodo->title;
		$todo->completed = $updatetodo->completed;
		$todo->save();
		return Response::eloquent($todo);
    }

    public function delete_index($id = null) 
    {
		$todo = Todo::find($id);

		if(is_null($todo))
		{
		     return Response::json('Todo not found', 404);
		}
		$deletedtodo = $todo;
		$todo->delete();     
		return Response::eloquent($deletedtodo);   
    } 

}

?>

That’s it! We are done with our API part, now let’s test it.

Go to the root of your application in the browser, you should see a default “Laravel installed” page, now go to your API route (the one we specified in routes.php):

api/v1/todos/

and you should see an empty JS array : []

If there is some kind of error, you need to troubleshoot it until you get an empty JS array on your API page.

Now launch your terminal if you are on Mac OS, and do simple CURL commands to see if the API is working. On my machine I execute the following commands and see the following output(replace “apitest/public” with URL to your app):

curl -H “Accept: application/json” -H “Content-type: application/json” -X GET http://localhost/apitest/public/api/v1/todos/

Output : [].

curl -H “Accept: application/json” -H “Content-type: application/json” -X POST -d ‘{“title”:”My First TODO”,”completed”:”no”}’ http://localhost/apitest/public/api/v1/todos/

Output: {“title”:”My First TODO”,”completed”:”no”,”updated_at”:{“date”:”2012-11-16 23:15:18″,”timezone_type”:3,”timezone”:”UTC”},”created_at”:{“date”:”2012-11-16 23:15:18″,”timezone_type”:3,”timezone”:”UTC”},”id”:1}

curl -H “Accept: application/json” -H “Content-type: application/json” -X PUT -d ‘{“id”:”1″,”title”:”MODIFIED My First TODO”,”completed”:”yes”}’ http://localhost/apitest/public/api/v1/todos/

{“id”:”1″,”title”:”MODIFIED My First TODO”,”completed”:”yes”,”created_at”:”2012-11-16 23:15:18″,”updated_at”:{“date”:”2012-11-16 23:18:29″,”timezone_type”:3,”timezone”:”UTC”}}

curl -H “Accept: application/json” -H “Content-type: application/json” -X DELETE http://localhost/apitest/public/api/v1/todos/1

Did it work? If yes, you are good to go, your API is now complete. You can play with it from the command line, but what fun is that?

In the next tutorial we will adapt TodoMVC Backbone application to our Laravel PHP API!

Stay tuned and subscribe to this blog via RSS or follow me on Twitter!

Update! Next part of the tutorial is published:
Building RESTful API in Laravel – part 3 – Integration with BackboneJS

You may also like

More in Blog, Code Blog
Hosting Bootsnipp, traffic and load testing your site with Blitz.

Bootsnipp is now in top 70,000 websites worldwide according to Alexa ratings (third month of Bootsnipp's existence) : I can't...

Close