0

I have built an API which essentially has three calls. Firstly, a call is made to retrieve a token. Next, I have a type of autocomplete feature which returns data and the coresponding table it should look up. This data is returned like so

[
  {
    "result": "Apples",
    "table": "fruitTable"
  },
  {
    "result": "Bread",
    "table": "breadTable"
  },
  {
    "result": "Pie",
    "table": "pieTable"
  }
]

My final route is like the following

Route::get('returnSelectedResult/{table}/{selected}', array('uses'=>'APIController@returnSelectedResult'));

Whereby it uses the lookup results above to get the right table and the selected option. Then I do the following

public function returnSelectedResult($table, $selected)
{
    $tableData = DB::table($table)->where('search_item', $selected)->get();
    return response($tableData, 200);
}

So this all works fine. However, the data in the table is flat. So the final thing returned to the user of the API is something like this

[
  {
    "search_item": "Bread",
    "num_types": 34,
    "most_ordered": 'Baggette',
    "most_popular_day": 'Saturday',
    "average_profit": 3.5,
  }
]

What I am showing is a very cut down version, there is a lot more data returned but it is all at the same level. What I need to return to the user is something more along the lines of this

[
  {
    "searched" : {
        "search_item": "Bread"
    },
    "types" : {
        "num_types": 34
    },
    "analytics" : {
        "most_ordered": 'Baggette',
        "most_popular_day": 'Saturday',
        "average_profit": 3.5
    }
  }
]

What would be the best way to achieve something like this?

Thanks

1
  • The best way is to reformat your array like you need
    – u_mulder
    Sep 24, 2016 at 11:12

3 Answers 3

1

You can explicitly build the array with the query results.

1
  • I was confused whether to do this, or if I needed to Model things. Sep 24, 2016 at 11:31
1

if you really want to build api you should use transformers for a better presentation of data .

you can use phpleague/fractal or if you want full api package i recommend you to try dingo/api .

1
  • fractal looks interesting, will take a look into it, thanks Sep 24, 2016 at 11:31
0

Do something like this, Now I have done for analytics

class MainClass
{
  public $searched;
  public $types;
  public $analytics;
}

class AnalyticsClass
{
  public $most_ordered;
  public $most_popular_day;
  public $average_profit;
}

$obj_data = new AnalyticsClass();
$obj_data->most_ordered = 'Baggette';  
$obj_data->most_popular_day = 'Saturday';
$obj_data->average_profit = 3.5;

$obj_main = new MainClass();
$obj_main->analytics = $obj_data; 

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.