PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, January 23, 2022

[FIXED] Modify data before pagination in CakePhp

 January 23, 2022     cakephp, json, pagination, php     No comments   

Issue

I'm trying to create an Api using cakephp. I generate a json on server and it works fine , but I tired to use pagination and I got a problem.

in the first case I take the image's path and I encode it to base64 and I generate json => works

in the second case I defined the pagination by the limits and the max and I kept the same code but as a result the image field is still the path from the database and it's not encoded

this my code in my controller :

class PilotsController extends AppController {
    public $paginate = [
        'page' => 1,
        'limit' => 5,
        'maxLimit' => 5
    ];

    public function initialize() {
        parent::initialize();
        $this->loadComponent('Paginator');
        $this->Auth->allow(['add','edit','delete','view','count']);
    }

    public function view($id) {
        $pilot = $this->Pilots->find()->where(['Pilots.account_id' => $id], [
            'contain' => ['Accounts', 'Pilotlogs']
        ]);
        foreach ($pilot as $obj) {
            if ($obj->image_pilot!= NULL) {
                $image1 = file_get_contents(WWW_ROOT.$obj->image_pilot);
                $obj->image_pilot = base64_encode($image1);
            }
        }
        $this->set('pilot', $this->paginate($pilot));
        $this->set('_serialize', ['pilot']);
    }
}

If I remove the pagination from the code it works fine . Any idea how to fix it ??


Solution

I'd suggest to use a result formatter instead, ie Query::formatResults(). So you'll have something like this :

public function view($id) {
$pilot = $this->Pilots->find()
->where(['Pilots.account_id' => $id], [
    'contain' => ['Accounts', 'Pilotlogs']]);
->formatResults(function($results) {
    return $results->map(function($row) {
        $image1 = file_get_contents(WWW_ROOT.$row['image_pilot']);
        $row['image_pilot'] = base64_encode($image1);
        return $row;
    });
});

}



Answered By - HAOUAS Khaled
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing