Eric Lee Eric Lee - 1 year ago 77
PHP Question

cakephp how to send data from controller to view with json

Hi I'm trying to make an API to send data encapsulating with json.

as cakephp manual said, I added extensions in routes.php


and I've made an index function in controller.

public function index(){
$item = $this->Items->find('all');
$this->set(['items' => $items, '_serialize' => ['items']]);

here are the problem.

what should i do after this to make api encapsulating with json??

Please help.

thank you

Answer Source

According to Cake 2.x Book (

You have to add this to your routes.php file:


Then, in your items controller, add the RequestHandler to your components array:

public $components = array('RequestHandler');

Then, in your items controller, add your methods, in your example:

public function index() {
    $recipes = $this->Items->find('all');
        'items' => $items,
        '_serialize' => array('items')

Note: according to model names convention you should call $this->Item instead of $this->Items unless you previously defined the model name as "Item" (singular) in your item model file.

Finally, the API is done, you can access to yourprojecturl/items.json and see the json result.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download