In cakephp 3.6, How to change user finder query for auth component?

261 Views Asked by At

For cakephp 3.6, cakephp.org tell how to customise user finder query for auth component at following link: link But I am not getting how to implement it? I have 'department_id' column in users table which belongs to departments table. I want to change the following query:

public function findAuth(){
    $query
    ->select(['id', 'username', 'password'])->contain(['Departments'])
        ->where(['Users.active' => 1]);
    return $query;
}

Will the above code work? Please tell me in which file I have to write the function? And what are other necessary steps to get it done, so that I get all user related info in $this->Auth->User ?

1

There are 1 best solutions below

0
On BEST ANSWER

Firstly, you will need to load the Auth component and pass in custom configuration in any controller that you want to use the custom finder like so:

public function initialize()
{
    parent::initialize();
    $this->loadComponent('Auth', [
        'authenticate' => [
            'Form' => [
                'finder' => 'auth'
            ]
        ],
    ]);
}

then, in your UsersTable you would have the custom finder:

public function findAuth(\Cake\ORM\Query $query, array $options)
{
    $query
    ->select(['id', 'username', 'password'])->contain(['Departments'])
    ->where(['Users.active' => 1]);

    return $query;
}

This answer may also help Containing tables in custom Auth finder