I'm working on a client website which part of it to retrieve news, this is my first codeigniter application and I have followed CI tutorials, slugs and routing.
The problem I'm having is that everything works fine but when it comes to get a record based on slug I get 404. What I did was removed index.php from my URL and tested it, which works fine.
This is my route.php
$route['default_controller'] = "welcome";
$route['404_override'] = '';
$route['news/(:any)'] = 'news/singe_news/$1';
$route['news'] = 'news';
This is my model news_model.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class News_model extends CI_Model {
function get_all(){
$sql="SELECT * FROM news AS news";
$query=$this->db->query($sql);
return $query->result();
}
//// get a single post
function get_single($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();
}
function news_categories(){
$sql="SELECT * FROM news_categories";
$query=$this->db->query($sql);
return $query->result();
}
}
and this is my controller news.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class News extends CI_Controller {
public function index()
{
$this->load->model('news_model');
$data['results']=$this->news_model->get_all();
$this->load->view('public/header', $data);
$this->load->view('public/menu');
$this->load->view('public/news-listing', $data);
$this->load->view('public/footer', $data);
}
public function single_news($slug) {
$this->load->model('news_model');
$data['single_news'] = $this->news_model->get_single();
/// if (empty($data['single_news']))
/// {
/// show_404();
///}
$this->load->view('public/header');
$this->load->view('public/menu');
$this->load->view('public/single-news', $data);
$this->load->view('public/footer');
}
}
So questions I have:
1- Where does $slug come from? I have a view has
2- Is there anything missing?
URLs need to be
domain.com/news/this-is-a-slug
Many thanks and apologies if this may have been asked in different format with different intention on other posts.
Where does $slug come from?
Your URI looks like this: www.example.com/controller/method/arg1/arg2/arg3 (w/o query string)
Is there anything missing?
Well, there is few things you should do:
Use autoload (config/autoload.php) to load your most used models, or if this model is not used widely at least load it at class constructor.
You are not passing $slug argument to model method, this will not work even if you will fix your routing.
$data['single_news'] = $this->news_model->get_single();
Better to show 404 if you can't find a slug, don't refetch all data on fail.
To fix 404 error follow those steps:
Check your .htaccess file for errors
Check uri_protocol setting in config
Try routing like this $route['news/((.+)$)?'] = "news/singe_news/$1"; (this should replace both routes for news)