Check if record exists in CakePHP3

bastey picture bastey · Jul 31, 2014 · Viewed 20.7k times · Source

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?

Answer

Jos&#233; Lorenzo Rodr&#237;guez picture José Lorenzo Rodríguez · Aug 4, 2014

You can do:

$fancyTable = TableRegistry::get('FancyTable');
$exists = $fancyTable->exists(['name' => 'fancy', 'active' => false]);