atastrophic
atastrophic

Reputation: 3143

Laravel REST API: Translating query string parameters into database search queries

I have been writing an API for my mobile application using Laravel 4 & Eloquent. I have read some details about writing a good API including Phil's Build a Decent API & apigee's RESTful API Design.

APIgee talks about sweeping complexity under query strings. Getting parameters from query string can be cumbersome because parameters could vary in number & types. For example to get a dog with black color, the request would be

http://url.com/api/dogs?color=black

And dog with black color & age would be

http://url.com/api/dogs?color=black&age=16

$dogs = new Dog;

if(Input::get('color'))
    $houses->where('color', '=', Input::get('color'));

if(Input::get('age'))
    $houses->where('age', '=', Input::get('age'));
// Keep adding more for every filter you have :-|

$dogs = $dogs->get();

An alternative & yet a better way was to use DB column names as param names and use a foreach loop to construct a query.

However, I was wondering if there was an alternative to this approach or if this is a standard approach in handling query strings.

Upvotes: 3

Views: 2471

Answers (1)

Nikhil Agrawal
Nikhil Agrawal

Reputation: 285

I think if you have a 3-4 parameters then you can check them indivisually as you have done above.

But if you have many parameter then you can use foreach loops, take precautions to avoid searching from hidden fields (like id)..Example below..

$inputs = Input::except('id', 'something_cannot_be_used_for_searching');

    foreach($inputs as $key => $input)
    {
     //Stmts
    }

Let me know if any other problem. Thanks :)

Upvotes: 1

Related Questions