I just pushed up a PR to CodeIgniter as a quality-of-life upgrade: a new "when()" method. This allows you to conditionally modify a query based on the truthiness of the given condition. Without breaking the chain.
For example, say you need to filter users based on an HTTP query var.
$status = service('request')->getPost('status');
$users = $this->db->table('users')
->when($status, static function ($query, $status) {
$query->where('status', $status);
})
->get();
Nice and simple. You can also give it a closure to run when the condition evaluates to false:
$onlyInactive = service('request')->getPost('return_inactive');
$users = $this->db->table('users')
->when($onlyInactive, static function ($query, $onlyInactive) {
$query->where('status', 'inactive');
}, static function ($query) {
$query->where('status', 'active');
})
->get();
Those of you who have used Laravel in the past will recognize this feature. It is such a handy thing that cleans up your code I thought we should borrow the feature.
What other quality-of-life improvements would you like to see in CodeIgniter?
You must be logged in via Patreon to leave a comment.