Passing Backbone fetch parameters to Laravel application

I’ve noticed that some people are having trouble using Backbone fetch function to pass parameters to their PHP applications.

In this very short post I’m going to fix that and demonstrate how to pass a query parameter during backbone fetch call so that the PHP application (running Laravel) will return specific data. For example the data could be sorted in different ways or it may be the data needs to be acquired dynamically based on what the user is doing and who the user is.

Backbone has a way of passing data with the fetch call before it fetches the data. Here is a short copy of the docs sections :

jQuery.ajax options can also be passed directly as fetch options, so to fetch a specific page of a paginated collection: Documents.fetch({data: {page: 3}})

Here is an example of Backbone Router that has fetches different data depending on what route you hit in the web application:

var Photo = Backbone.Model.extend({  
            initialize: function(){},  
            defaults: {  
                location: 'photourl',  
                id : 1  
            }  
        });    

var PhotoCollection = Backbone.Collection.extend({  
    model : Photo,
    url: "http://127.0.0.1/yourapp/public/photos" 
});

var photos = new PhotoCollection;  

var AppRouter = Backbone.Router.extend({
    routes: {
        ""      : "showNew",
        "new"   : "showNew",
        "top"   : "showTop",
        "random": "showRandom"
    },

    showNew: function(){
        photos.fetch({ data: {sortby: "new"}});  
    },

    showTop: function() {
        photos.fetch({ data: {sortby: "top"}});  
    },

    showRandom: function() {
        photos.fetch({ data: {sortby: "random"}});  
    }

});

All that’s left is implement these different query parameters in the Laravel app, here is a short copy paste of my route that returns real data (model called “photos” ) sorting it in different ways depending on the Query parameter that we pass from Backbone fetch function :

Route::get('photos', function()
{
	$sortby = Input::get('sortby', 'new');
	switch ($sortby) {
		case 'new':
			return Response::eloquent(Photo::order_by('created_at', 'desc')->get());
			break;
		case 'top':
		    $photos =  DB::query('SELECT photos.*, COUNT(photos.id) AS captions
				FROM photos LEFT JOIN captions ON photos.id = captions.photo_id
				GROUP BY photos.id
				ORDER BY captions DESC');

			return Response::json($photos);	
			break;
		case 'random':
			return Response::eloquent(Photo::order_by(DB::raw(''),DB::raw('RAND()'))->get());
			break;
		default:
			return Response::eloquent(Photo::order_by('created_at', 'desc')->get());
			break;
	}
});

That’s it, this is all there is to passing parameters during Backbone fetch calls!

Enjoy

Liked it? Take a second to support Maks Surguy on Patreon!
Become a patron at Patreon!

You may also like

8 comments

  • Álvaro Carneiro February 16, 2013  

    Really usefull, thanks, some day I’ll start using Backbone.js (you’re inspiring me to use it).
    Some things I’d like to change in your code: http://paste.laravel.com/hPq

  • Maks Surguy February 16, 2013  

    thank you, that code is certainly more beautiful, appreciate it!!!
    I’m going to post it on the Laravel forum as an update to mine.

    Thanks so much for checking it out and improving, I really need more people to review my code!

  • Shirish Nigam February 17, 2013  

    Hi Maks,

    Very useful article indeed. Btw i bought your course on Laravel on udemy already and i must say it was a great tutorial. thanks for for putting it up there.

    Do you have any plans to create advanced backbone course on udemy ?

    I have to ask you a question regarding Laravel 3.2.13, is the Model::find(id) method broken in this version or it’s just me doing something wrong because find method returns all the records instead of the one i’m looking for.

    if you can confirm it as a bug or point me in right direction that would be much appreciated.

    Thanks heaps

    Shirish

  • Maks Surguy February 17, 2013  

    Thanks for buying my course!

    I am not aware of a bug with model::find method, can you point me to some code snippets from what you are trying to do?

    I wish I could do another Laravel course focusing on Backbone but unfortunately my job right now keeps me pretty busy…

  • Shirish Nigam February 19, 2013  

    Hi Maks,

    Here is my simplistic code
    http://paste.laravel.com/i70

    because Model::find didn’t worked for me so i had to use Model::where instead in my working code but for your reference i modified it to use find.

    Please have a look when you have time.
    Much appreciate your input.

    Thanks

    Shirish

  • Maks Surguy February 19, 2013  

    I think your if statement is set up incorrectly.

    I am most positive it executes
    Invoice::order_by('invoice_no','asc')->get()
    in either case of the if statement.

    You need to check if the element exists, for example :
    $invoice=Invoice::find($id)->get();
    and then check for $invoice == null to see which records you want to show, all of them or just specific one.
    Let me know if that works

  • Shirish Nigam February 20, 2013  

    Thanks for your input. I have pinpointed what’s wrong with my code.

    If i modify the call to the below line i get correct result and get only requested record

    $invoice=Invoice::find($id);

    but if i execute the below line, seems line find method gets ignored and i get all the records from table

    $invoice=Invoice::find($id)->get();

    Do you think the second call should return the correct result ?

  • Maks Surguy February 26, 2013  

    Actually it works as expected, according to the docs : “The get method will return an array of models, while the first method will return a single model:”

Leave a comment