Search code examples
phpcakephpurl-routingcakephp-3.0

Cake3 How to capture all characters in path property for rest routes


So, I have a piece of code, for my routes, like this:

Router::scope('/v1', function (RouteBuilder $routes) {
    $routes->resources( 'Files', [
        'map' => [
            'index' => ['action' => 'index', 'method' => 'GET', 'path' => ''],
            'create' => ['action' => 'add', 'method' => 'POST', 'path' => ''],
            'view' => ['action' => 'view', 'method' => 'GET', 'path' => ':id'],
            'update' => ['action' => 'edit', 'method' => ['PUT', 'PATCH'], 'path' => ':id'],
            'delete' => ['action' => 'delete', 'method' => 'DELETE', 'path' => ':name'],
        ]
    ]);
});

And I have a URL like: http://192.168.1.197/v1/files/13625a1ddedcbc2011-40115501.jpg

And I want 13625a1ddedcbc2011-40115501.jpg to be the :name parameter you see in the 'delete' => ['action' => 'delete', 'method' => 'DELETE', 'path' => ':name'] route above, however, no matter what I do (I even tried regex here) I get the error:

Too few arguments to function App\Controller\FilesController::delete(), 0 passed in

I have read the documentation on it maybe a thousand times: https://book.cakephp.org/3.0/en/development/routing.html but I cannot figure out how.

I took a look at this answer, it is a bit vague on how to use it and it would mean I change ALL routes to be like this: How to give string in the url in RESTful api in Cakephp? which I don't want to do.

How can I capture this parameter?


Solution

  • I had some "fun" with the map as well and gave up on it and did this:

    $routes->connect('/:model/:foreignKey/:commentId', [
        'plugin' => 'Burzum/Comments',
        'controller' => 'Comments',
        'action' => 'edit',
        '_method' => 'PUT'
    ], [
        'pass' => [
            'model',
            'foreignKey',
            'commentId'
        ],
        '_ext' => null,
        'model' => $allowedModels,
        'commentId' => $idRegex,
        'foreignKey' => $idRegex,
    ]);
    

    Let me know if the concept is clear for your or not. If not I'll change it to your actual case.