Mittul At TechnoBrave
Mittul At TechnoBrave

Reputation: 1242

How to get current controller action in cakephp 3.x model

I am using cakephp 3.x have put database queries in model in which i want to check the current controller action and based on that i will make my database queries.

I know i can pass controller action from my controller itself to my model function but is there a way i can just check my current controller action inside my model only so that i do not need to pass it in my multiple functions which are inside model only.

My Try -- UsersTable.php

    public function initialize(array $config)
    {
        parent::initialize($config);
        $this->table('users');        
        $this->primaryKey('user_id');
        echo '<pre>';
        print_r($GLOBALS);        
        exit;
    }

so far if i do this, i got an array in response and in which i found this the best result out of other things in that array

[REQUEST_URI] => /5p_group/users/add

I m also trying to use this

echo '<pre>';
print_r($GLOBALS['_SERVER']['HTTP_REFERER']);        
exit;

which gives me this output

http://localhost/5p_group/users/archived

so eventually i am getting the result which i want but i want another proper method which cakephp 3.x uses ..

So is there any other way or more frequent way from that i can get my current controller action ?

Any ideas will be appreciated ..

Thanks

Upvotes: 2

Views: 3679

Answers (2)

ᴍᴇʜᴏᴠ
ᴍᴇʜᴏᴠ

Reputation: 5276

The question was about a Model, but it shows up on Google.

When inside a view (.ctp file), use

\Cake\Routing\Router::getRequest()->getAttributes();

CakePHP 3

Upvotes: 0

Rohit Ailani
Rohit Ailani

Reputation: 910

First of all you should use the routing class in your model. So at the top you can call it like below

use Cake\Routing\Router;

And then in your initialize function you can check the params like

debug(Router::getRequest());

Or to be more specific you can use

debug(Router::getRequest()->params['action']);

I think this is the solution using cakephp classes only, though a small hack.

For more function reference you can access the cookbook at Router Class

Upvotes: 5

Related Questions