cloudcreativity / laravel-json-api

JSON API (jsonapi.org) package for Laravel applications.
http://laravel-json-api.readthedocs.io/en/latest/
Apache License 2.0
780 stars 109 forks source link

Cutsom response without ORM Model #432

Closed jk100magnys closed 3 years ago

jk100magnys commented 5 years ago

Hello! I've tried to make custom route with custom controller and I want to send to client some calculated data. But I couldnt wrap this data to API Response

Route JsonApi::register('default')->routes(function ($api) { $api->get('/Food', 'FoodController@index'); });

Controller #1 ` $obj = new \stdClass(); $obj->name = "Foo";

    $data = json_api()->encoder()->serializeData($obj);
    return json_api()->encoder()->encodeData($data);`

Error No JSON API resource type registered for PHP class stdClass.

or other way

Controller #2 ` $arr = ['foo' => 'bar'];

    $data = json_api()->encoder()->serializeData($arr);
    return json_api()->encoder()->encodeData($data);`

Error get_class() expects parameter 1 to be object, string given

So, the questions 1) How I can return custom data from that controller? 2) How I can make Schema & Adaptor for Instance not based on Eloquent (because I want to have url for calculated object without DB table)?

Thank you.

lindyhopchris commented 5 years ago

When you use serializeData or encodeData, it's expecting the PHP classes that you register in the resources part of your API's config. I.e. passing in a \stdClass is not going to work, because there is no schema for it.

The encoder that this package uses expects a PHP class to have a registered schema. Therefore if you want to do a schema for non-Eloquent data, it needs to have a PHP class. We tend to use entity classes for this kind of thing... then you can run the generators, e.g. make:json-api:resource with the flag to indicate you want the generated adapter/schema etc to not relate to an Eloquent model.

lindyhopchris commented 3 years ago

Closing this due to lack of activity.