LoadModel in CakePHP 5

Hi, previously i used loadmodel in cakephp 4, but i cakephp 5, it seem like it deprecated and cannot use anymore. I used the loadmodel to get data from table settings in app controller. Anybody can assist me on this issue? Thanks…

class AppController extends Controller
{
    public function beforeFilter(\Cake\Event\EventInterface $event)
	{
		parent::beforeFilter($event);
	
		$this->loadModel('Settings');
		$this->set('system_name', $config->get('system_name'));
	}
2 Likes

loadModel has been deprecated since CakePHP 4.3

Use

$this->Settings = $this->fetchTable('Settings');

instead.

you also should add the property

protected \App\Table\SettingsTable $Settings;

to your class as well to not get PHP warnings after going to PHP 8.2+

4 Likes

Thank you for your reply. I’ve revised and used the following code. I hope it helps others, too. At least, it was a new lesson for me. Thanks @KevinPfeifer

class AppController extends Controller
{
    public function beforeFilter(\Cake\Event\EventInterface $event)
	{
		parent::beforeFilter($event);
	
		$this->fetchTable('Settings');
		$config = $this->Settings->find('all')->first();

		$this->set('system_name', $config->get('system_name'));
	}

but fetchTable() doesn’t automatically set a property (like loadModel() did in the past). It only returns the table instance.
So if this works for you you can remove the $this->fetchTable('Settings'); as well and you probably set the table instance somewhere else…

But i can’t use the findByName anymore?
For the information: I have a brands table with ID and Name column.

$this->fetchTable('Brands');

$brand = $this->Brands->findByName($bus->brand)->first();

I get the error: Call to a member function findByName() on null

if you didn’t add a findByName() method to your BrandsTable class then sure, this can’t work.

CakePHP’s finders are built differently like you can see here

As @KevinPfeifer said above, fetchTable just returns the table object, it doesn’t set a property. So $this->fetchTable('Brands'); does NOT mean that now $this->Brands is set. Hence why you’re seeing, “Call… on null”. Do $this->Brands = $this->fetchTable('Brands'); and you’ll at least get a different error message. :slight_smile:

In CakePHP 5, you should use the Table Locator to load models. Replace $this->loadModel('Settings') with the provided code to load the “Settings” model in your AppController. It’s a minor adjustment due to changes in CakePHP’s version.

That should be

protected \App\Model\Table\SettingsTable $Settings;