Need Help with Routing Error in CakePHP

Hey everyone,

I’m relatively new to CakePHP and currently building my first website with it. I’ve run into a routing error that I can’t seem to figure out.

The error message I’m getting is:

Missing Route: /users/add

When I was searching about this and I came across to this resources CakePHP 3.* Prefix routing error - Stack Overflow what is react native, and as per them I tried the following.

I’ve checked my routes in config/routes.php, and here’s what I have:

use Cake\Routing\RouteBuilder;
use Cake\Routing\Router;

Router::plugin('MyPlugin', function (RouteBuilder $routes) {
    $routes->connect('/users/add', ['controller' => 'Users', 'action' => 'add']);
});

I also have a UsersController.php with the add method defined:

namespace App\Controller;

use App\Controller\AppController;

class UsersController extends AppController {
    public function add() {
        $user = $this->Users->newEmptyEntity();
        if ($this->request->is('post')) {
            $user = $this->Users->patchEntity($user, $this->request->getData());
            if ($this->Users->save($user)) {
                $this->Flash->success(__('The user has been saved.'));
                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('Unable to add the user.'));
        }
        $this->set('user', $user);
    }
}

Despite having these set up, I keep encountering the “Missing Route” error whenever I try to access /users/add. I’m not sure what I’m doing wrong here. Could anyone point me in the right direction or suggest what I might be missing?

Thanks in advance for any help!

Cheers,

The fact that you do Router::plugin('MyPlugin' leads in the following route being added:
/my_plugin/users/add

If you don’t want to wrap your routes inside that my-plugin scope then you will have to define the plugin where the controller lives in like so

$routes->connect('/users/add', ['controller' => 'Users', 'action' => 'add', 'plugin' => 'MyPlugin']);

just without the Router::plugin('MyPlugin' wrapper

You can check all available routes via bin/cake routes to make sure what you did is actually what you expect

1 Like

When trying to figure out why routes aren’t working I find it useful to use the cake cli to list all the routes.

bin/cake routes