Search code examples
codeigniter-routing

Codeigniter routing how to permit null parameter


I want paginate my index http:localhost/mysite/home but if I write only this http:localhost/mysite/home the page said: "page not found", but if I write http:localhost/mysite/home/3 its work! how to I can configure my routing to get null parameters? I tried with (:any) and (num) but not work

My route file is:

       $route['404_override'] = 'welcome/no_found';
       $route['home/'] = "welcome/home/$1";

My controller:

      $config['base_url'] =  base_url().'/mysite/home';
      $config['total_rows'] = $this->mtestmodel->countNews();
      $config['per_page'] = 2; 
      $config['num_links']   = 20;
      $this->pagination->initialize($config); 
      $data['paginator']=$this->pagination->create_links();
      $data['news']=$this->mtestmodel->show_news( $config['per_page'],intval($to) );

//$to is a parameter in url base_url()/mysite/home/3


Solution

  • Change your route.php file to the following:

    $route['404_override'] = 'welcome/no_found';
    $route['home/(:num)']  = "welcome/home/$1";
    $route['home']         = "welcome/home";
    

    This way, your application will catch both requests (http://localhost/mysite/home and http://localhost/mysite/home/3), and will send them both to your controller.

    You should then be able to access your $to variable (which has been passed as the first argument into your controller's function) or use $this->uri->segment(2) instead.

    e.g.

    public function home($to = 0) {
        $config['base_url']    =  base_url().'/mysite/home';
        $config['total_rows']  = $this->mtestmodel->countNews();
        $config['per_page']    = 2; 
        $config['num_links']   = 20;
        $this->pagination->initialize($config); 
        $data['paginator']     = $this->pagination->create_links();
        $data['news']          = $this->mtestmodel->show_news( $config['per_page'],intval($to) );
    
    }
    

    Hope that helps!