Categories
CakePHP Career PHP Tips and Tricks

Loading Model Inside Another Model and Controller in CakePHP 3

Sometimes it necessary to load a model inside another model as well as another controller in CakePHP. This article will help you to load a model from another model & controller with CakePHP 3

Sometimes it necessary to load a model inside another model as well as another controller in CakePHP. This article will help you to load a model from another model & controller with CakePHP 3

Load From Model:
$anotherTable = TableRegistry::get('AnotherTable');
$data = $anotherTable->find('list');

CakePHP TableRegistry is a factory of the Table object. It comes with a lot of static function and get() one of them. TableRegistry::get() provides an instance of Table. You can see an example from above snippet.

Load From Controller:
$this->loadModel('AnotherModel');
$data = $this->AnotherModel->find('list');

If you need to load a model from the controller which does not default model of the controller. You can use loadModel() function to get an instance of another model.

By Sohel Rana

PHP Programmer, Software Engineer & Technology lover

Leave a Reply

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