简体   繁体   中英

Laravel REST API with query parameters

So I have part of an API up and running, but am stuck on a few things. I am working with Laravel's REST controllers and am loving the ability to use methods such as Response::eloquent($query); But, in using this:

  1. How should I handle query parameters (eg id=27&order_by=timestamp), if the resource that I am getting is joining several tables?
  2. Should I get the values from the database, and then construct an array with only the certain fields that I want to display for API access? And how would this then work with query parameters?

First off I would recommend that you watch Teach a Dog to REST [Link broken] for more information about formatting your REST routes.

As for your questions:

  1. You can handle input fields through the Input::get() and Input::all() methods as mentioned in laravel input & cookies docs . You might also have to validate incoming data with laravel's Validator class.
  2. Say you acquired the id and order_by fields from the input as mentioned in your example:

    $id = Input::get('id'); $order_criteria = Input::get('order_by');

using Fluent Query Builder

DB::table('dbtable')->where('id', '=', $id)->order_by($order_criteria, 'desc')->first();

// Using first() since we are pretty sure that we are getting only one result out, for a different criteria where more than a result could be returned you might want to use ->get() instead.

I released a package for this.

You can check this out https://github.com/selahattinunlu/laravel-api-query-builder

For wiki page: https://github.com/selahattinunlu/laravel-api-query-builder/wiki

This package creates query with url parameters.

Example:

/api/users?name=se*&age!=18&order_by=age,asc&limit=2&columns=name,age,city_id&includes=city

And resulting query

Users::with(['city'])->select(['name', 'age', 'city_id'])
                     ->where('age', '!=', 18)
                     ->where('name', 'like', 'se%')
                     ->orderBy('age', 'asc')
                     ->take(2)

Usage:

$queryBuilder = new QueryBuilder(new User, $request);

return response->json([
  'data' => $queryBuilder->build()->paginate(),
  .
  .
]);

That's all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM