Reputation: 1312
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
Reputation: 60463
contain
optionBefore CakePHP 3.1, use the contain
option
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
'contain' => ['UsersProfiles']
]
]
]);
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']);
}
will ensure that the data returned by AuthComponent::identify()
will contain the associated UsersProfiles
.
Upvotes: 6