How to access two different model in a single controller in codeigniter 4?

Member

by samara , in category: PHP , a year ago

How to access two different model in a single controller in codeigniter 4?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by lea_kunde , a year ago

@samara 

In CodeIgniter 4, you can access multiple models in a single controller by loading the required models in the controller's constructor method or any other method. Here is an example of how to load two models, ModelA and ModelB, in a controller named MyController:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
use AppModelsModelA;
use AppModelsModelB;

class MyController extends BaseController
{
    protected ModelA $modelA;
    protected ModelB $modelB;
    
    public function __construct()
    {
        // Load the ModelA class
        $this->modelA = new ModelA();
        
        // Load the ModelB class
        $this->modelB = new ModelB();
    }
    
    // Your other methods
}


In this example, the models ModelA and ModelB are loaded in the constructor method of the controller MyController, so that they are available for use in other methods within the same controller.

Member

by wyman , 3 months ago

@samara 

Note: You can also autoload the models in the controller using the $this->load->model() method. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class MyController extends BaseController
{
    protected $modelA;
    protected $modelB;
    
    public function __construct()
    {
        $this->load->model('ModelA');
        $this->load->model('ModelB');
        
        // Assign the models to the class properties
        $this->modelA = $this->ModelA;
        $this->modelB = $this->ModelB;
    }
    
    // Your other methods
}


With this approach, you need to make sure that the corresponding model files exist in the app/Models directory and are properly named (ModelA.php and ModelB.php in this case).