Quantcast
Channel: User Hamfri - Stack Overflow
Viewing all articles
Browse latest Browse all 42

Answer by Hamfri for Cakephp3: How can I return json data?

$
0
0

As of cakePHP 4.x.x the following should work assuming that your controller and routes are set as shown below:controller: <your_project_name>/src/Controller/StudentsController.php

public function index()    {        $students = $this->Students->find('all');        $this->set(compact('students'));        $this->viewBuilder()->setOption('serialize',['students']);    }

Routes: <your_project_name>/config/routes.php

<?phpuse Cake\Routing\Route\DashedRoute;use Cake\Routing\RouteBuilder;/** @var \Cake\Routing\RouteBuilder $routes */$routes->setRouteClass(DashedRoute::class);$routes->scope('/', function (RouteBuilder $builder) {    $builder->setExtensions(['json']);    $builder->resources('Students');    $builder->fallbacks();});

Run bin/cake server and visit http://localhost:8765/students.json using postman/insomnia or just the normal browser.See further documentation for setting up Restful controllers and Restful Routing

Don't forget to set the method to GET on postman and insomnia.


Viewing all articles
Browse latest Browse all 42

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>