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!
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') ) );
You could achieve it by first set a router config item within the config file ( the default file is located at application/config/config.php ), for example :
$config['routes']['insertUser'] = 'users/add';
then supply the config above into the standard routes item on routes.php,
$route[$this->config->item('routes')['insertUser']]['post'] = 'UserController/insert';
and then on the view you could call it dynamically like this :
echo form_open( base_url( $this->config->item('routes')['insertUser'] ) );
So each time if you have to change the route you just change on the config.php.
I just recently solved this issue. Was trying to add it to a HADEOAS Transformer. It took me a long time dissecting CI4's route handler to replicate Laravel's route($name)
helper. But I got it. Enjoy:
https://gist.github.com/kmuenkel/21fca746022c19f7bff7b1de940db45e