• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to use two models in a controller

#1
Hello everyone, this is about codeigniter 4.

I wanta use two models in a controller. But I have no idea how to solve it. Any suggestion for me please ? 

PHP Code:
<?php namespace App\Controllers;

use 
CodeIgniter\HTTP\IncomingRequest;
use 
CodeIgniter\Controller;
use 
App\Models\CompanyModel;
use 
App\Models\AuthenticationModel;

class 
Login extends BaseController
{   
    
protected $request;
    protected $companyModel;
    protected $authenticationModel;
    
    
public function __construct()
    {
        // Call the Model constructor
        $this->request service('request');
        $this->companyModel = new CompanyModel();
    }

    public function index()
    {
        $data = [
            'name' => $this->companyModel->name()
        ];

        echo view('authentication'$data);
    }

    public function process()
    {
        
        $this
->authenticationModel = new AuthenticationModel();
        $username $this->request->getPost('username');
        $password $this->request->getPost('password');

        $boolen $this->authenticationModel->authentication($username$password);

        return $boolen;
    }

Reply

#2
Your example works just fine. Personally, I'd use the model() helper just to ensure I don't get more than 1 instance of the model created, but what you've done works fine.

EDIT:

if you're just using a model in a single method, there's no need to assign it to $this, just use a local variable:

PHP Code:
$authenticationModel = new AuthenticationModel();
$username $this->request->getPost('username');
$password $this->request->getPost('password');

$boolen $authenticationModel->authentication($username$password); 
Reply

#3
(05-11-2020, 06:40 AM)kilishan Wrote: Your example works just fine. Personally, I'd use the model() helper just to ensure I don't get more than 1 instance of the model created, but what you've done works fine.

EDIT:

if you're just using a model in a single method, there's no need to assign it to $this, just use a local variable:

PHP Code:
$authenticationModel = new AuthenticationModel();
$username $this->request->getPost('username');
$password $this->request->getPost('password');

$boolen $authenticationModel->authentication($username$password); 


kilishan, thank for your reply. I will edit about this ~
Reply


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.