A lightweight package that adds Laravel-style sole()
behaviour to CodeIgniter 4 models.
Ensures that a query returns exactly one record, otherwise throws an exception.
composer require sambenge/codeigniter4-sole
In your model:
use CodeIgniter\Model;
use Bengey\Sole\SoleTrait;
class UserModel extends Model
{
use SoleTrait;
protected $table = 'users';
}
Then, in your service or controller:
$userModel = new UserModel();
try {
$user = $userModel->where('email', 'john@smith.com')->sole();
// Do something with $user
} catch (\Bengey\Sole\Exceptions\RecordNotFoundException $e) {
// No records found
} catch (\Bengey\Sole\Exceptions\MultipleRecordsFoundException $e) {
// More than one record found
}
The sole()
method is useful when you expect a query to return exactly one record. It helps to enforce this expectation by throwing exceptions if the result set is empty or contains multiple records. This can help to prevent bugs and ensure that your application behaves as expected.