Search code examples
phpcodeigniterslugcodeigniter-routing

CodeIgniter: I'm able to list the items but I can't load one


My

Application/.htaccess

RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]

Application/config/routes.php

$route['default_controller'] = "news";
$route['404_override'] = '';

Application/models/news_model.php

<?php
class News_model extends CI_Model {

    public function __construct()
    {
        $this->load->database();
    }

    public function get_news($slug = FALSE)
    {
        if ($slug === FALSE)
        {
            $query = $this->db->get('news');
            return $query->result_array();
        }

        $query = $this->db->get_where('news', array('slug' => $slug));
        return $query->row_array();
    }
}
?>

Applications/controlers/news.php

<?php
class News extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->model('news_model');
    }

    public function index()
    {
        $data['news'] = $this->news_model->get_news();
        $data['title'] = 'News archive';

        $this->load->view('templates/header', $data);
        $this->load->view('news/index', $data);
        $this->load->view('templates/footer');
    }


    public function view($slug)
    {
        echo $slug;
        $data['news_item'] = $this->news_model->get_news($slug);
        var_dump($data);
        if (empty($data['news_item']))
        {
            show_404();
        }

        $data['title'] = $data['news_item']['title'];

        $this->load->view('templates/header', $data);
        $this->load->view('news/view', $data);
        $this->load->view('templates/footer');
    }
}
?>

Applications/views/index.php:

<?php foreach ($news as $news_item): ?>
    <?php var_dump($news_item); ?>
    <h2><?php echo "<pre>"; echo $news_item['title'] ?></h2>
    <div id="main">
        <?php echo $news_item['text'] ?>
    </div>
    <p><a href="news/<?php echo $news_item['slug'] ?>">View article</a></p>

<?php endforeach ?>

And Applications/views/view.php

<?php
echo '<h2>'.$news_item['title'].'</h2>';
echo $news_item['text'];

The problem is that I can see index (wich lists my news) but when I click on a slug link it tries to go to:

/news/slug1

And it fires a not found error..

What am I missing here?


Solution

  • Link should be:

     <p><a href="/news/view/<?php echo $news_item['slug'] ?>">View article</a></p>