Helping you solve those tough coding problems!

Changes to Model:find('first') in CakePHP 2.3 Changes to Model:find('first') in CakePHP 2.3

Published on Jan 30, 2013 by Jamie Munro

A new stable release of CakePHP has just been released a few days ago, version 2.3.  With this many great new changes have come out of it.  You can read the full change log here:

One of the things that immediately caught my mind was this great big bolded sentence:
IMPORTANT: Model::find('first') will now return an empty array when no records are found. Make sure you update your tests!

Immediately after reading this I thought major code changes were going to be required; however, luckily my fear was unfounded.  Let me provide an example...

Here is a typical query that I would perform:

$user = $this->User->find('first', array('conditions' => array('id' => $id)));

Previously this function would return null if no results were found; however, no as you can see it will return an empty array.  After performing this function I would either in my controller or in my view execute the following code to detect if a user was found or not:

if ($user) {
// User found, do something
} else {
// No user found

Have no fear, even after this subtle change, the code still works as expected.


If your unit tests are asserting that the variable is null these will fail as it now must assert that count array is equal to 0.  Nice and simple, so remove panic :)

Tags: CakePHP | cakephp 2.3 | CakePHP

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP