Cakephp create a simple API

This tutorial for cakephp version 4, here we will learn how we can create a simple API using cakephp.

Our goal is we will create an API to save category if doesn’t exist !

Very beginning we will create a resources route in cakephp. Here, you may ask what is the resource route ? Answer is resource route will accept all http VERBS. Example GET,POST,PUT,DELETE,PUT

Now let’s go in cakephp source in location config/routes.php Go to the end of the line and create a new route scope for your API. Example 

$routes->scope('/api', function (RouteBuilder $routes) {

       'path' => 'category',
       'prefix' => 'Api',
       'map' => [

           'addCategory' => [
               'action' => 'addCategory',
               'method' => 'POST',
               'path' => '/add-category'

Here , You can see I have created a route for my categories controller where I have an action called addCategory

So, Let’s create a class in location src/Controller/Api
Note : Create a folder with name Api, because in route we have used prefix Api

Now your CategoriesController.php will looks like below.



namespace App\Controller\Api;
use App\Controller\AppController;
use Cake\Event\EventInterface;
use Cake\ORM\TableRegistry;

Class CategoriesController extends AppController 
   public function addCategory()

       $category = $this->Categories->patchEntity($this->Categories->newEmptyEntity(), $this->request->getData());
                       return $category;
       $this->viewBuilder()->setOption('serialize', ['category']);

Don’t forget to create a model for categories ! You can use a simple bake command to create a model for categories table.

bin/cake bake model categories

So, We have done it ! Now let’s test in postman , you can test it postman using below URL


Set body name = your-category-name

Also send a post request !

Cakephp get last month summary report.

Example we have a table called transactions.Where transactions has 3 fields 

Id | amount | created 

We need to fetch last month’s summary by the created date. So, in cakephp we can write like below

public function report()

       $targetDate = FrozenTime::now()->modify('1 month ago');
       $query = $this->Transactions->find();
               'amount'=> $query->func()->sum('Transactions.amount')
           'Transactions.created >=' => $targetDate->startOfMonth(),
           'Transactions.created <=' => $targetDate->endOfMonth()

Here I have used cakephp FrozenTime class.
So, top in our class we have to use

use Cake\I18n\FrozenTime;

In view you can write below foreach loop to print data.

<?php foreach ($transactions as $transaction): ?>
             <td><?= $transaction->created->format("Y-m-d") ?></td>
             <td><?= $transaction->amount ?></td>
 <?php endforeach; ?>

Cakephp gives a limit on associative/relational data.

Example we have two tables, one is articles and another is comments table. Articles hasMany relations with comments. 

Example our articles table looks like 


id |  title | created | modifier 


Id | comment | article_id | created | modified 

Assuming in articles table we have build  a  hasMany relation with comments like below example


$this->hasMany('Comments', [
     'foreignKey' => 'article_id',

Here, article_id is the foreign key.

Now, in the ArticlesController/index method we will write a query where we want only the last two comments. 

So, we can write our index method like below

public function index()
   $article = $this->Articles->find()
       ->contain('Comments', function($q){
       return $q
              ->order(['Comments.created' => 'DESC']);

So now in view you will get articles with 2 recent comments.

CakePHP sum a column then group by month.

I have below sql query to get summation of a column name amount , where the result will be grouped by month.

  MONTHNAME( created ) as monthname,
  sum( amount ) as total

Example, In transactions table I have an amount field where the amount is a numeric value field and transactions have created and modified fields.

So, we can write this query in query builder like below way

public function index()
    $query = $this->Transactions->find();
        ‘monthname’ => $query->func()->monthname([
            ‘created’ => ‘identifier’
         ‘total’ => $query->func()->sum(‘Transactions.amount’)

After iteration we should get the result like below

monthname  total
July                    100
May                  300
….. …..

CakePHP 3 : Change Default Layout

To change default layout in CakePHP, We need to go in cakephp AppController.php

In AppController we have to write cakephp beforeFilter method.
beforeFilter() method is executed before every action in the controller.

It will like below example :

Location : src/Controller/AppController.php

Note : Write this method after initialize() method in AppController
Continue reading “CakePHP 3 : Change Default Layout”