1

Not sure if this is a php or cakephp question. I am using cakephp ver3.1.3. I have a cakephp query object $query that look like this when I call debug($query->toArray());

[
    (int) 0 => object(App\Model\Entity\Customer) {

        'id' => (int) 1,
        'username' => 'asd',
        'password' => '123',
        'fullname' => 'asd',
        'email_addr' => 'asd@gmail.com',
        '[new]' => false,
        '[accessible]' => [
            '*' => true
        ],
        '[dirty]' => [],
        '[original]' => [],
        '[virtual]' => [],
        '[errors]' => [],
        '[repository]' => 'Customers'

    }
]

When I call json_encode($query), it looks like this;

[
    {
        "id": 1,
        "username": "asd",
        "password": "123",
        "fullname": "asd",
        "email_addr": "asd@gmail.com"
    }
]

How do I process $query such that when I call json_encode($query), the output will look like this?

[
    {
        "email_addr": "asd@gmail.com"
    }
]
guagay_wk
  • 26,337
  • 54
  • 186
  • 295

1 Answers1

2

To only receive the field 'email_addr' from the database, modify your query using the method select():

$query->select(['email_addr']);

If you want to remove all other fields after the query already ran, you can just loop over the array and modify the elements:

$simplified = array();
foreach($query as $row) {
    $simplified[] = array(
        'email_addr' => $row->get('email_addr')
    );
}
echo json_encode($simplified);

On a side note, an important warning: Do not, under no circumstance, store passwords in clear text. Read this answer, specifically the section about storing passwords!

Community
  • 1
  • 1
Lars Ebert
  • 3,487
  • 2
  • 24
  • 46
  • While the second part of @LarsEbert's answer will work for entities you have already loaded, there's a simpler method: [use the `$_hidden` property](http://book.cakephp.org/3.0/en/orm/entities.html#hiding-properties) in the Customer entity to set which fields should not be encoded. For example, in your Customer entity class definition: `protected $_hidden = ['id', 'username', 'password', 'fullname'];` – Greg Schmidt Sep 22 '15 at 23:58