PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, April 2, 2022

[FIXED] Cakephp how can I created a route for accept both id and cat id with maintain path?

 April 02, 2022     cakephp, cakephp-4.x     No comments   

Issue

I have an API prefix route, I have a controller where I'm trying to fetch product, then products by id , then products by category id.

So, I have created a prefix route

$routes->scope('/api', function (RouteBuilder $routes) {
        $routes->setExtensions(['json']);
        $routes->resources('Shops',[
            'prefix' => 'Api',
            'path' => 'shops',
            'map' => [
                'getProducts' => [
                    'action' => 'getProducts',
                    'method' => 'GET',
                    'path' => '/products'
                ],
                'getProductById' => [
                    'action' => 'getProducts',
                    'method' => 'GET',
                    'path' => '/products/{id}',
                ],
                'getProductBySubcatId' => [
                    'action' => 'getProducts',
                    'method' => 'GET',
                    'path' => '/products/cat/{cat_id}',
                    'subcat_id' => [0-10]
                ],
            ]
        ]);
 });

In action actually I'm trying to do

public function getProducts($id = null, $cat_id = null)
{   
        if($id)
          -----
        else if($cat_id)
          ----
}

I need to fetch the data like

http://localhost:8000/api/shops/products/cat/1.json

Present For below URL

http://localhost:8000/api/shops/products/1.json

I'm getting params pass

protected params => [
'id' => '1',
'pass' => [
   (int) 0 => '1',
],

But for catId I'm not getting pass http://localhost:8000/api/shops/products/cat/1.json

protected params => [
'catId' => '1',
'pass' => [ ],

Also I'm able to send string as a params for cat id

protected params => [
'catId' => 'A',
'pass' => [ ],

How can I add catId in pass ? also how can I add a validation that catId always int ?


Solution

You can solve it using connectOptions

map [
  // your map 
],
'connectOptions' => [
    'catId' => '[0-9]+',
    'pass' => ['id','catId'],
],

For details check RouteBuilder.php class



Answered By - Alimon Karim
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing