URL Alias for Contrloler/Method in CodeIgniter 4

50 Views Asked by At

In CodeIgniter 3 I could do this in the Config/Routes.php file: $routes->get('Net_Price', 'SomeController::SomeNonIndexMethod'); 'Net_Price' is an alias (for the lack of a better term). And the URL to access this Controller/Method was: www.example.com/Net_Price (I could even use capital letters in the alias.)

I want to do exactly this - in CodeIgniter 4. Is it possible?

The closest I've gotten is if I put the following route into Config/Routes.php (of CI4). $routes->match(['get', 'post'], 'SomeController/SomeNonIndexMethod', 'SomeController::SomeNonIndexMethod', ['as' => 'Net_Price']); Then I can do redirect()->route('Net_Price') (not redirect()->**to**('Net_Price') what does redirect()->to even do?) in SomePrecedingMethod of the controller. And the correct URL is being called by the browser. BUT, the SomeNonIndexMethod method being routed to also needs the POST data from the SomePreceedingMethod method and / or from the view. Anyway, currently I can route to the alias OR get the Post data without a Redirect. Please do not cite redirect()->withInput() -- I've tried it, and seems to only work if you're trying to go BACK to a previous page / method.

An example of your solution would be most helpful.

1

There are 1 best solutions below

1
J. Robert West On

@Antony was correct and his comment is the answer.

For clarification: The CI3 code was actually $route['Net_Price'] = 'SomeController/SomeNonIndexMethod'; In reformatting that code for CI4 -- specifically adding the get, post, or match part -- I was getting confused, and my actual route-code was like $routes->match(['get', 'post'], 'SomeController/SomeNonIndexMethod', 'SomeController::SomeNonIndexMethod', [as => 'Net_Price'] Basically, I had gotten it into my head that in order to call the method in the route-code I had to use BOTH SomeController/SomeNonIndexMethod AND SomeController::SomeNonIndexMethod in each route. When, in fact, the 'slashed-bit' can be anything you want it to be -- the 'double-colon'd-bit' (not used in CI3 routes) is the actual controller-method reference.

The correct CI4-formatted route is: $routes->match(['get', 'post'], 'Net_Price', 'SomeController::SomeNonIndexMethod');

Finally, the 'slashed-bit' (whether it has a slash or not) is what the View needs to reference in CI4.