9

I'm building my first CodeIgniter application and I need to make URLs like follows:

controllername/{uf}/{city}

Example: /rj/rio-de-janeiro This example should give me 2 parameters: $uf ('rj') and $city ('rio-de-janeiro')

Another URL possible is:

controllername/{uf}/{page}

Example: /rj/3 This example should give me 2 parameters: $uf ('rj') and $page (3)

In other words, the parameters "city" and "page" are optionals. I can't pass something like '/uf/city/page'. I need always or 'city' OR 'page'. But I don't know how to configure these routes in CodeIgniter configuration to point to same method (or even to different methods).

3 Answers 3

17

I've found the correct result:

$route['controllername/(:any)/(:any)/(:num)'] = 'ddd/index/$1/$2/$3';
$route['controllername/(:any)/(:num)'] = 'ddd/index/$1/null/$2'; // try 'null' or '0' (zero)
$route['controllername/(:any)'] = 'ddd/index/$1';

The Index method (inside "ControllerName") should be:

public function Index($uf = '', $slug = '', $pag = 0)
{
    // some code...

    if (intval($pag) > 0)
    {
        // pagination
    }

    if (!empty($slug))
    {
        // slug manipulation
    }
}

Hope it helps someone. Thank you all.

3
  • It still doesn't pass the 'null' in my case. I always get the next parameter on this place.
    – V.Vachev
    Commented May 7, 2014 at 12:31
  • 3
    @V.Vachev try to pass 0 (zero) instead null. Commented Oct 31, 2014 at 16:56
  • That's exactly how I did it, and it works correctly. Null seems to be some 'special/reserved' word for the routes. It definitely has different behavior.
    – V.Vachev
    Commented Nov 4, 2014 at 7:35
1
public function my_test_function($not_optional_param, $optional_param = NULL)
  { 
   //do your stuff here
  }

have you tried this?

2
  • Yes. But the second parameter is variant. Sometimes is a string (city slug), other times is a number (page). Commented Sep 24, 2013 at 5:06
  • Great! I can also use Regular Expressions instead of ":any" and ":num". Thanks. Commented Sep 24, 2013 at 5:19
0

For example, let’s say you have a URI like this:

  1. example.com/index.php/mycontroller/myfunction/hello/world
  2. example.com/index.php/mycontroller/myfunction/hello

Your method will be passed URI segments 3 and 4 (“hello” and “world”):

class MyController extends CI_Controller {

public function myFunction($notOptional, $optional = NULL)
{
    echo $notOptional; // will return 'hello'.
    echo $optional; // will return 'world' using the 1st URI and 'NULL' using the 2nd.
}

}

Reference: https://codeigniter.com/user_guide/general/controllers.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.