Search code examples
codeigniterundefined-variable

Severity notice: Undefined variable - images_model


This code works well in the "images" view under images_model:

<?php if($images_model):?>
    <?php foreach($images_model as $images):?>
        <div class="col-sm-4">
            <div class="well">

                <img src="<?php echo base_url()."uploads/".$images->name;?>" alt="" class="img-thumbnail">  

The code in images_model is the following:

function save_image($data){     
    $this->db->insert('images', $data);
}

When I try to use the same code in the "wall" view (main_controller) I get the severity notice error saying "images_model" is undefined; even though I load the images_model in the main_controller or auto-load the both models:

$autoload['model'] = array('main_model', 'images_model');

I originally questioned the "foreach" code in the "images" view, but I thought if it works in one view shouldn't it also work in another if I load the related model? It just doesn't seem to be reading the images_model.

I'm just getting to know codeigniter a bit and would appreciate any feedback.


Solution

  • Are you passing the $images_model variable to your view from your main_controller ?

    // Set your variable
    $data['images_model'] = $images_model;
    
    // Pass variable to view
    $this->load->view('main', $data);
    

    You typically shouldn't have access to a model directly in the view (following MVC principals). Your controller should get what it wants from the model, then pass it to the view.