Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a database-generated menu on every page in CodeIgniter?

I'm using CodeIgniter and have a menu on the site that needs to read a list of cities from the database. This is simple to do if it's just on one or two pages - I load the model and call a function from the controller, and pass the data into the view.

But if I want it on every page, that means I have to keep copying the same code to every single controller function and pass the data into the view. (Note, I'm using a separate "header" view that contains the menu.)

What's the best way to automatically load some data on every page load and have it available to my view?

like image 220
DisgruntledGoat Avatar asked Dec 28 '22 14:12

DisgruntledGoat


1 Answers

Create a new root controller class like MY_Controller.

You can read how here: https://www.codeigniter.com/user_guide/general/core_classes.html

Then make all your controllers extend that class.

Add a function in MY_Controller like this:

function show_view_with_menu($view_name, $data) {
   $menu_data = $this->menu_model->get_menu(); // load your menu data from the db
   $this->load->view('header', $menu_data); // display your header by giving it the menu
   $this->load->view($view_name, $data); // the actual view you wanna load
   $this->load->view('footer'); // footer, if you have one
}

Whenever you normally do load a view, instead do this:

$this->show_view_with_menu('view_for_this_controller', $data);
like image 179
icchanobot Avatar answered Feb 01 '23 23:02

icchanobot