3

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.

1
  • Is there a reason why you have $dogs = $dogs -> get() and not including the query filters in the get() method? I'm trying to do the same as you but can't seem to get your code to work for my API. Commented Apr 3, 2016 at 22:36

1 Answer 1

1

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 :)

Sign up to request clarification or add additional context in comments.

2 Comments

i would love to generalize this code, move to model or validation, define exceptions & run query there. I guess I'd have to stick to foreach loops for that as well.
You can use query scope laravel.com/docs/eloquent#query-scopes if you want to do that in your model and re-use it easily. I would also use an array containing a whitelist of acceptable parameters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.