Building RESTful API in Laravel – part 3 – Integration with BackboneJS

For those of you who haven’t been following this blog – I am posting a short series of tutorials that guide you through creating a simple API in Laravel 3 and integrating it with a client application – in this case TodoMVC BackboneJS application (see screenshot below).

Part 1 of the tutorial is here : https://maxoffsky.com/code-blog/building-restful-api-in-laravel-start-here/

And part 2 is here: https://maxoffsky.com/maxoffsky-blog/building-restful-api-in-laravel-part-2-design-api-controller/

In this tutorial we will look at the changes that we need to make to get TodoMVC (BackboneJS version) working with the API we created in previous tutorials.

If you haven’t checked out TodoMVC before, please take a look at some of its examples : http://addyosmani.github.com/todomvc/

We will be adapting the BackboneJS example found here : http://addyosmani.github.com/todomvc/architecture-examples/backbone/

So go ahead and look through its source code here.

Now, starting with our API source code, I left the default index.blade.php under application/views/home folder erased its contents and created a page that looks like the BackboneMVC page, with the following structure:

  • Load css in the header.
  • Skeleton HTML (header, input field for new todos, empty UL element)
  • Underscore templates (item-template and stats-template)
  • Necessary JS libraries (json2.js, jQuery.js, underscore.js, Backbone.js)

What I did then was to put all of the Todo JS app files into one giant script for easier management while developing so don’t be surprised when you look at my source and see that it is all together.

The original Backbone TodoMVC is using localStorage as a store for the data, we will use our API and the server to actually save the data.

So first thing, we need to comment out localstorage usage from the source code under TodoList Collection, find this line and comment it out:

//localStorage: new Store('todos-backbone'),

Now, we need to specify a URL for the model to do its magic Fetch and Sync methods, in this case it will be our API we created previously, so in the same code block add the following line (you can add it as the first line in the TodoList Collection):

url :"./api/v1/todos",

That’s it!

Now your code should look like this :

var TodoList = Backbone.Collection.extend({
	url :"./api/v1/todos",
	// Reference to this collection's model.
	model: app.Todo,

	// Save all of the todo items under the `"todos"` namespace.
	//localStorage: new Store('todos-backbone'),
...

Believe it or not, that is all we need to do to make our app work!

Try it out and see if you can create new todos!

I have encountered a small problem with passing JSON values for true/false to my API so the script would take a JSON string like this “completed” : “0” and interpret the 0 as true. Therefore I modified my database structure to take a string instead of a number for the “completed” field and changed the JS code to return “yes” and “no” instead of “true” / “false”. Maybe you know of a better solution? Let me know in the comments.

Update by user psycketom:
using Laravel Eloquent’s getters / setters (in L3, not covered) or accessors / mutators (in L4):

// add to Todo model
// getter/accessor
public function getCompletedAttribute($value)
{
return (bool) $value;
}

// setter/mutator
public function setCompletedAttribute($value)
{
$this->attributes['completed'] = (int) $value;
}

The source code for the whole application (including API and the Boxfile for PagodaBox deployment) is posted on Github get it here:

https://github.com/msurguy/LaravelBackboneTodoMVC

You may also like

  • I used this tutorial as a guide to set up Laravel 4 with Backbone.

    I encountered similar problem as you had with the “completed” attribute, but, I just not read the question.

    Yes, I think I have a better workaround, using Laravel Eloquent’s getters / setters (in L3, not covered) or accessors / mutators (in L4):

    // add to Todo model
    // getter/accessor
    public function getCompletedAttribute($value)
    {
    return (bool) $value;
    }

    // setter/mutator
    public function setCompletedAttribute($value)
    {
    $this->attributes[‘completed’] = (int) $value;
    }

    This did it for me.

    Basically, what it does, is always casts upon getting the value to boolean, and whenever setting, casts to integer.

    One more thing, for future, in Step 2, I’d suggest you explain how to add the table through migrations.

  • Maks Surguy

    Thanks for posting this, and for the suggestion! I will update the post right now.

  • Pingback: Building RESTful API in Laravel - part 2 - Design API Controller - Maxoffsky |()

  • Seemab Hassan

    HI Maks. Been following u for a long time. I am building a thing of mine. Its a mobile application which I am going to create using phonegap and API using laravel. The only thing I can’t understand is that how do I add login to it. And how to authenticate if a user is logged in or not. Any help would be appreciated.. 🙂

  • maxsurguy

    You can use regular “cookie-based authentication” without doing anything fancy. Don’t overthink it, here’s my tutorial on login with Backbone + Laravel: https://maxoffsky.com/code-blog/login-to-laravel-web-application-from-phonegap-or-backbone/

More in Blog, Code Blog
blogAPI
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...

Close