Search code examples
codeignitercodeigniter-4

$this->load does not work on Codeigniter 4


I get error if I use with $this->load->view(... but it works if I use echo view(... Error is : Call to a member function view() on null

I get same error if I try to load a model with $this->load->model(...


Solution

  • Output directly to browser with echo view('') If you want to get a view and for example send though ajax use return view('')

    This is new in CI4, there is not more $this->load->view('')

    Note that if the last line of the execution is return view('') it still is passes to the browser.

    All this applies to models and libraries. Now its more OO rather than having a super object.

    For example if you have a model located under App/Models, in the controller or where you want to load it include the namespace i.e. use App\Models\MyModel at the beginning and then in method you want to use just create a new class i.e.

    $myModel = new MyModel();
    

    If you want an instance of a library helper for example the db in you model do this constructor for your model:

    protected mixed $db;
    public function __construct(ConnectionInterface &$db)
    {
        $this->db = &$db;
    }
    

    In the base controller initController method put

    $this->db = \Config\Database::connect();

    Now when you create an instance of the model from a controller which extends BaseController pass the db instance:

    $myModel = new MyModel($this->db);
    

    Note that $this in CI4 does not refere to the superobject but to the controller instance i.e. whatever you load in initController can be found in $this. There are several helpers and libraries that in CI4 now are loaded by default such as $this->request->getPost('')

    Please read the documentation CI4 Documentation especially if you are used to CI3