Search code examples
phpcodeigniter-4

Codeigniter 4, call a controller method in a seeder


Morning guys, I'm searching on how to call a function of a controller in my seeder file.

Account Controller

public function createCompte() {
    //generate an account number
        return $numcompte;
    }
}

seeder

public function run(){
    $compteController = new CompteController;
    $numcompte = $this->compteController->createCompte();
    $data_client = [ 
           //other data generate with faker
            'num_cmpte_client' => $numcompte ,
           
        ];
    $id_client = $this->db->table('client')->insert($tab);
 }

Solution

  • As noted by @Pippo in a comment:

    You are assigning the controller instance to a local variable $compteController but then you are calling his method createCompte() using another varibale that seems to be a property of the seeder $this->compteController->createCompte()

    So;

    Instead of:❌

    $numcompte = $this->compteController->createCompte();
    

    Use this:✅

    $numcompte = $compteController->createCompte();
    

    Reference(s):

    1. What does the variable $this mean in PHP?
    2. php.net: $this