CakePHP 2: Useful AppModel methods

I realise I haven’t posted anything in over a year, this is due to being extremely busy in day by day life, however I’ll give it another shot by posting some useful methods you may add to your AppModel in CakePHP 2.x

Extending Exists
You’ve more than likely used exist quite often, it’s available in every model and allows you to check if the field with the primary key exists. You may then do another method call to check if it belongs to a specific field, well this simple extension gives you the ability to do all that in one

You may now call $this->MyModel->exists($primaryKey, $userId);  to check if the record exists to the $userId passed. It’s not limited to .user_id, you can specify a third parameter to check against any other foreign key for example on a user you may do the following to check if the user is an admin user_type.


Do Two Fields Match?
This is quite a simple yet effective validation rule, if you wish to make sure the value of two fields in the same form submit match, you can call on this.

Now from any model, you can specify the validation rule, here’s an example of how to compare password to password_confirm for User.


Check Against Config
If you take advantage of CakePHP’s Configure::write() and Configure::read() throughout your application, there may come a time you wish to check the input of a form against one of these particular config values. Here’s a handy validation method to do just that.

Here is an example usage from an application I have worked on, I have trimmed out anything unrelated.


Check Past/Future Date
This one is pretty straight forward for validation rules, it allows you to check the date passed is in the future or in the past, you use it just by passing the method name without a parameter.


This is a useful method for when you need to soft delete or hard delete a record, it’s quite simple really in all it does is detect if you have a ‘deleted’ field on your record and if so toggle it to 1, otherwise delete via primary key. Note: It’s up to you to make sure you don’t query records with deleted set to 1 to give the effects of it being deleted.


So I’ll finish up with a nice easy simple one, this one allows you to get the last query ran by CakePHP which can be very helpful for debugging at times.


Leave a Reply

Your email address will not be published. Required fields are marked *