prakashchhetri
prakashchhetri

Reputation: 1816

Using model in views / controller in codeigniter

I use codeigniter for web development. As I am learning it more, I am finding some more issues that I cannot get a proper logical implementation.

I have a article_controller.php and a view article.php . I am trying to display all of the article titles on the page. (This code is just for testing purpose).

Lets say I have another table named images which contains all the images used in the article. So can I use the images_m.php model on the article.php view.

Article_Controller.php

$data['articles'] = $this->article_m->get(); //gets all of the articles 
$this->load->view('articles',$data);

Article.php

foreach($articles as $article):
    echo $article->title;
    $images = $this->images_m->get_by(array('article_id'=>$article->id)); //gets all the images for current article

    foreach(images as $image):
        echo "<img src='./uploads/".$image->filename ."'/>";
    endforeach; 

endforeach;

The code works perfectly fine. I have used similar code in a number of websites. But the main issue is, I have read that it is not a good idea to use models in views. Use models in controllers instead.

So how can I fetch the images for a particular article in a controller.

Upvotes: 2

Views: 418

Answers (2)

stormdrain
stormdrain

Reputation: 7895

Something like this (pseudo-code) might work:

Controller:

$articles = $this->article_m->get();
$images = array();

foreach($articles as $article):
    $images[$article->id] = array();

    $article_images = $this->images_m->get_by(array('article_id'=>$article->id));
    foreach($article_images as $image):
        $images[$article->id][] = './uploads/'.$image->filename;
    endforeach; 
endforeach;

$data['articles'] = $articles;
$data['images'] = $images;

$this->load->view('articles',$data);

View:

foreach($articles as $article):
    echo $article->title;

    foreach($images[$article->id] as $image):
        echo "<img src='$image'/>";
    endforeach; 

endforeach;

Basically just do the same work you were doing in the view and do it in the controller instead. Then throw it in the $data array and send it to the view.


Edit: I'd recommend looking at @dianuj's answer :)

Upvotes: 2

M Khalid Junaid
M Khalid Junaid

Reputation: 64466

Get images in your controller and merge the images object with each article object and pass it to view

$articles= $this->article_m->get(); //gets all of the articles 

foreach($articles as $article):

    $article->article_images = $this->images_m->get_by(array('article_id'=>$article->id)); //gets all the images for current article   
endforeach;

$data['articles']=$articles;
$this->load->view('articles',$data);

MAke sure you have loaded the images_m model in controller

Upvotes: 3

Related Questions