Home > Back-end >  Codeigniter 4 - route now working / 404 / Controller or its method is not found
Codeigniter 4 - route now working / 404 / Controller or its method is not found

Time:02-13

Here are a couple of my routes;

This one works:

$routes->get('/admin/users', 'Admin/User/User_Controller::user_index');

This one doesn't work:

$routes->get('/admin/toggle_user_is_active/(:num)','Admin/User/User_Controller::toggle_user_is_active/$1');

As you can see, it is calling the same method. The passed in value is a userid like 72. If active is 1 in the db it then sets it to 0 and vice verse, thus the name toggle_user_is_active($id).

If I put directly in URL as follows:

https://example.com/admin/toggle_user_is_active/72

I get the following error:

404 file not found
Controller or its method is not found: \App\Controllers\Admin::index

The toggle in the view is as follows:

<a href="<?= site_url('admin/users/toggle_user_is_active/'.$user->id)?>"> Toggle </a>  

When clicked it produces:

https://example.com/admin/toggle_user_is_active/72

Scratching my head! Any pointers appreciated.

CodePudding user response:

Namespaces are defined using backslashes (\), not forward slashes (/).

Instead of:
'Admin/User/User_Controller::toggle_user_is_active/$1'

Use this:
'Admin\User\User_Controller::toggle_user_is_active/$1'

Name resolution rules

Qualified name

This is an identifier with a namespace separator, such as Foo\Bar

Setting your own routing rules

The controller and method should be listed in the same way that you would use a static method, by separating the fully-namespaced class and its method with a double-colon, like Users::list.

  • Related