Search code examples
phpcodeigniterurlviewroutes

Calling routes from a view in CodeIgniter


I would like to avoid hard-coding urls in the views.

Example:

//view
echo form_open( base_url( 'users/add' ) );...

//routes
$route['users/add']['post'] = 'UserController/insert';

This way every time I update the url in routes, I have to go to view, find the form and manually update the url in view which can be very taxing.

In laravel you can name a route like this:

//routes.php
$route->post('users/add', 'UserController@insert')->name('insertUser');

and call it directly from view with a helper function

//view
form_open( routes('insertUser') );...

This way you the url in the view updates automatically, and saves you the trouble of doing it manually.

I'm wondering if there is something similar in CodeIgniter.

Thanks in advance!


Solution

  • The way that laravel implements it is simply by giving a name to the route which you can already do it yourself in codeingniter by using $config[] simply by creating a new config file in your app/config and name your route as you did in laravel like this:

    $config['insertUser'] = 'users/add';
    

    Then load that config file in your controller like this:

    $this->load->config('your_config_file_name');
    

    Then in your view you can use that value like this:

    form_open( base_url( $this->config->item('insertUser') ) );