How can I load model to helper? I need to load it outside of functions, but use them in functions.
1 Answer. Show activity on this post. You could get a reference to the controller object and access the model through that. Another option is to pass the model in when calling the helper function.
Syntax (call model method) – Create a User. php file in application/controllers directory. Load above created Main_model using $this->load->model('Main_model') method in the __construct() method and call getUsers() method using $this->Main_model->getUsers() . Store the return response in a $data variable.
Approach 1 (Invoking them in controller files): In order to load multiple helper files in the PHP working environment, we can specify them in an array as components where each of the components corresponds to a helper name.
CodeIgniter does not load Helper Files by default, so the first step in using a Helper is to load it. Once loaded, it becomes globally available in your controller and views. Helpers are typically stored in your system/Helpers, or app/Helpers directory. CodeIgniter will look first in your app/Helpers directory.
You could get a reference to the controller object and access the model through that.
function my_helper() { // Get a reference to the controller object $CI = get_instance(); // You may need to load the model if it hasn't been pre-loaded $CI->load->model('my_model'); // Call a function of the model $CI->my_model->do_something(); }
Another option is to pass the model in when calling the helper function.
function my_helper($my_model) { $my_model->do_something(); } function my_controller_action() { // Call the helper function, passing in the model my_helper($this->my_model); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With