SeaSky
SeaSky

Reputation: 1312

How to retrieve associations together with authenticated user data?

I have a Users table and a UsersProfiles table - the two are obviously related and the user table stores basic user_id, username, password while the users_profiles table stores firstname, lastname, job_title etc.

In CakePHP 3, the call to Authentication Component on login returns the basic user table row. I would like to modify the same to also return the corresponding profile row. How can I do this?

I found a way to do it - but am not sure if there is a more elegant or simpler way.

public function login() {
        if ($this->request->is('post')) {
            $user = $this->Auth->identify();
            if ($user) {
                // load profile and associate with user object
                $profile = $this->Users->UsersProfiles->get($user['id']);
                $user['users_profile'] = $profile;
                $this->Auth->setUser($user);
                return $this->redirect($this->Auth->config('loginRedirect'));
            }
            $this->Flash->error(__('Invalid username or password, try again'));
        }
    }

Upvotes: 4

Views: 1242

Answers (1)

ndm
ndm

Reputation: 60463

The contain option

Before CakePHP 3.1, use the contain option

$this->loadComponent('Auth', [
    'authenticate' => [
        'Form' => [
            'contain' => ['UsersProfiles']
        ]
    ]
]);

A custom finder

As of 3.1 you can use the finder option to define the finder to use for building the query that fetches the user data

$this->loadComponent('Auth', [
    'authenticate' => [
        'Form' => [
            'finder' => 'auth'
        ]
    ]
]);

In your table class

public function findAuth(\Cake\ORM\Query $query, array $options)
{
    return $query->contain(['UsersProfiles']);
}

Both solutions

will ensure that the data returned by AuthComponent::identify() will contain the associated UsersProfiles.

See also

Upvotes: 6

Related Questions