26

In CakePHP 2 I always used empty to check if there any result.

<?php
$result = $this->Modelname->find('first', ['conditions' => ['field' => 'value'] ] );
if ( empty($result) ) {
// Bad Request
}

In CakePHP 3 it looks weird to me.

$fancyTable = TableRegistry::get('FancyTable');        
$query = $fancyTable->find()->where(['name' => 'fancy', 'active' => 0]);          

if ( 0 === $query->count() ) {
    // Bad Request
}

Is this the right way?

Sehdev
  • 5,486
  • 3
  • 11
  • 34
bastey
  • 668
  • 2
  • 11
  • 17
  • You can use isEmpty() now, added in CakePHP 3.0.4 ... [see similar question](http://stackoverflow.com/a/30011905) – Oops D'oh Aug 09 '15 at 20:03

2 Answers2

55

You can do:

$fancyTable = TableRegistry::get('FancyTable');
$exists = $fancyTable->exists(['name' => 'fancy', 'active' => false]);
  • how can i use the where condition in exists. like i want to know the existence of an field based upon the two parameters.? – tech_geek Mar 21 '18 at 14:04
  • 2
    An update to this answer now that `TableRegistry::get()` has been deprecated. Instead, use: `TableRegistry::getTableLocator()->get($table);` – Warren Sergent Jan 22 '19 at 22:26
  • Cakephp 3.* also you can use this method. `$exists = $tableName->exists([condition]);` – Marwan Salim Jul 07 '19 at 07:38
7

Use something like this:

if ($query->isEmpty()) {
    // Query or result set is empty
}
BadHorsie
  • 14,135
  • 30
  • 117
  • 191
Krunal Dave
  • 272
  • 6
  • 16
  • I don't know why this answer was voted down. It works and doesn't require another query (for exists) that Lorenzo's answer does. I vote it up. – cpliu338 Aug 19 '16 at 06:48
  • @cpliu338 possibly because if you do this in conjunction with `first()`, it doesn't work (at least not in the latest Cake). In which case if you still only wanted one record returned, you could just add `->limit()`, and still use this approach. – toast Jul 13 '17 at 06:49
  • @cpliu338 actually the preferred way of checking if `first()` is empty, or exists is it check if the result is null or not. This works better than `limit(1)` in this instance, as `limit` returns a collection. – toast Jul 13 '17 at 08:26