Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
CakePHP - beforeFind() callback with default conditions and possibility to disable it
public function beforeFind($event, $query, $options, $primary)
// if query builder have ->applyOptions(['default' => false]) not use default conditions and return query
if (isset($options['default']) && $options['default'] == false) {
return $query;
// default conditions
$query->where([ 'visible' => 1 ]);
$query->order([ 'sort' => 'ASC' ]);
return $query;

This comment has been minimized.


This comment has been minimized.

Copy link
Owner Author

arturmamedov commented Mar 5, 2018

For disabel it from Controller on selecting use ->applyOptions(['default' => false]) example:

// beforeFind() will be apply: `visible = 1 ORDER BY sort ASC`
$tips = TableRegistry::get('Tips')->find()->where(['site_id' => $this->projectId])->limit(4)->all();

// beforeFind() will not be apply
$tips = TableRegistry::get('Tips')->find()->applyOptions(['default' => false])->where(['site_id' => $this->projectId])->limit(4)->all();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.