I am currently using this code in laravel to create a new account, but I want to retrieve the ID generated for this account
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
I want to do this, to also give permission to the police
$data['id']->syncRoles($data['roles']),
create method return the created elocuent model, and you can manage like:
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
if($user)
$user->syncRoles($data['roles']);
return $user;
Related
I want to use another table instead of users for authentication. I know I can change the table name in User.php as follows:
protected $table = 'WhatEver';
But this is not what I want. I want to change the name in the backend of the application so that a completely different model is used. How can I achieve that? What files do I need to change?
I found the solution. First create a new database table, which should have password and remember_token fields. In config/auth.php change the providers section as follows:
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\NEW_MODEL_NAME::class,
],
After that, you need to alter App/Controller/Auth/RegisterController.php:
protected function validator(array $data) {
return Validator::make($data, [
'surname' => 'required|string|max:255',
'firstname' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:NEW_DB_TABLE_NAME',
'password' => 'required|string|min:6|confirmed',
]);
}
protected function create(array $data) {
return App\NEW_MODEL_NAME::create([
'surname' => $data['surname'],
'firstname' => $data['firstname'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
That's it.
I want to extend validation setting another field just like that:
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
'another_field' => 'validation'
]);
you can make your own validation case by follwing the documentation :)
If you need to change the message only, you can do it by
$messages = [
'required' => 'The :attribute field is required.',
'email' => 'This is a wrong e-mail address message I wrote myself.',
];
$rules = [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
'another_field' => 'validation'
];
return Validator::make($input, $rules, $messages);
I'm using CakePHP 2.8.5. It's not letting me log in "Username or password is incorrect". This seems totally straightforward in the docs but it isn't working for me. I wonder if my model/data structure might be confusing CakePHP. I have a Users model, but the logins are associated with an Admins model. The login form and action are in the Pages model (it has forms for multiple models).
in AppController:
public $components = array(
'DebugKit.Toolbar',
'Flash',
'Session',
'Auth' => array(
'userModel' => 'Admin',
'authenticate' => array(
'Form' => array(
'fields' => array(
'username' => 'email',
'password' => 'password'
),
'passwordHasher' => 'Blowfish'
)
),
'loginAction' => array(
'controller' => 'pages',
'action' => 'login',
),
'logoutRedirect' => array(
'controller' => 'pages',
'action' => 'login',
),
'authError' => 'Please log in',
'authorize' => array('Controller')
)
);
My login view, in /View/Pages. "email" is the username field:
<?php
echo $this->Form->create('Admin');
echo $this->Form->input('email');
echo $this->Form->input('password');
echo $this->Form->end('Submit');
?>
PagesController:
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirect());
} else {
$this->Flash->error(__('Username or password is incorrect'));
}
}}
Top of Admin model:
App::uses('BlowfishPasswordHasher', 'Controller/Component/Auth');
Automatic Blowfish encryption in Admin model:
public function beforeSave($options = array()) {
if (isset($this->data['Admin']['password'])) {
$passwordHasher = new BlowfishPasswordHasher();
$this->data['Admin']['password'] = $passwordHasher->hash(
$this->data['Admin']['password']
);
}
return true;
}
I notice if I enter the same password for different Admins, I get a different encryption result, but I've read that's normal.
If you want to see anything else, I'll add it.
The userModel key is in the wrong place
Compare the config in the question:
public $components = array(
'DebugKit.Toolbar',
'Flash',
'Session',
'Auth' => array(
'userModel' => 'Admin',
'authenticate' => array(
'Form' => array(
'fields' => array(
'username' => 'email',
'password' => 'password'
),
'passwordHasher' => 'Blowfish'
)
),
To the config in the docs:
$this->Auth->authenticate = array(
'Basic' => array('userModel' => 'Member'),
'Form' => array('userModel' => 'Member')
);
In the question userModel is a top-level key, in the docs it is part of the individual authenticate keys. Looking at the api examples (or the doc blocks in the source code) the error is more clear:
... you can define settings that should be set to all authentications objects using the 'all' key:
$this->Auth->authenticate = array(
'all' => array(
'userModel' => 'Users.User',
'scope' => array('User.active' => 1)
),
'Form',
'Basic'
);
It is possible to define a global userModel for all authenticate objects to use, but the syntax is simply different than the question.
Use the all key
Therefore to define a user model to use for all authenticate options, use the all key:
public $components = array(
'DebugKit.Toolbar',
'Flash',
'Session',
'Auth' => array(
//'userModel' => 'Admin', // <- no
'authenticate' => array(
'all' => array(
'userModel' => 'Admin' // <- yes
),
'Form' => array(
'fields' => array(
'username' => 'email',
'password' => 'password'
),
'passwordHasher' => 'Blowfish'
)
),
I'm developing a API in YII2 with multiple databases. I want to choose the database in real time. The idea is to read one variable available in controler (API key) to identify the correct connection database in model.
For example in webapplication like a portal i have (it works):
in db default connection i have
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=dbcompany_0',
'username' => 'root',
'password' => 'XXXXXXXXXXXXXXXXXXXX',
'charset' => 'utf8',
],
In model I have
public function tableName()
{
$schema = '';
$user = User::find(Yii::app()->user->id);
$schema = "dbcompany_". $user->CompanyId;
return $schema . '.' . 'customer';
}
With this approach I just have a single db connection for all database companies.
How I can apply the same\similiar approach in API. I don't have sessions.
Any idea is well welcome.
Create a new component under db as:
'db1' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=dbcompany_0',
'username' => 'root',
'password' => 'XXXXXXXXXXXXXXXXXXXX',
'charset' => 'utf8',
],
'db2' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=dbcompany_0',
'username' => 'root',
'password' => 'XXXXXXXXXXXXXXXXXXXX',
'charset' => 'utf8',
],
And use it as:
Yii::$app->db1
Yii::$app->db2;
All requests are authenticate using a token and this is associated to the user. When the authentication is done YII Framework assigns the userid to \Yii::$app->user->identity->id. So from anywhere I can identify the company owner in model.
public static function tableName(){
$moreinfo= account\Userextra::findOne(\Yii::$app->user->identity->id);
$schema = \Yii::$app->params['table.prefix'] . $moreinfo->CompanyId;
return $schema . '.country';
}
I am using CakePHP 2.3, I want to save data as follows follows:
$insertUser = array(
'Name' => $Name,
'LastName' => $lastName,
'password' => $password,
'email' => $email,
'TimeStamp' => $presentTime,
'RefererUserId' => $refererId // set the referer user id
);
$this->SystemUser->saveAll($insertUser) // save record in table.
The above code is not working. I tried another method like:
$this->SystemUser->query("INSERT INTO system_users(Name,LastName,password,email,TimeStamp,RefererUserId) VALUES ('{$Name}','{$lastName}','{$password}','{$email}','{$presentTime}','{$refererId}')");
How can I now get the last inserted id? I used getLastInsertId() to get last inserted id, as below:
$lastid = $this->SystemUser->getLastInsertId();
But it does not seem to work.
Please try the below code. SystemUser is assumed as your model name.
$this->user_data = array(
'SystemUser' => array(
'Name' => $Name,
'LastName' => $lastName,
'password' => $password,
'email' => $email,
'TimeStamp' => $presentTime,
'RefererUserId' => $refererId // set the referer user id
));
if ($this->SystemUser->save($this->user_data)) {
$lastid = $this->SystemUser->getLastInsertId();
} else {
// do something
}
Your $insertUser should be the following
$insertUser['SystemUser'] = array(
'Name' => $Name,
'LastName' => $lastName,
'password' => $password,
'email' => $email,
'TimeStamp' => $presentTime,
'RefererUserId' => $refererId // set the referer user id
);
Then you should be save data as like
if($this->SystemUser->save($insertUser)) {
$lastid = $this->SystemUser->getLastInsertId();
} else {
debug($this->SystemUser->validationErrors); die();
}
This will probably give you the info you need (assuming it's not saving because of invalid data, of course):
debug($this->SystemUser->validationErrors); die();
That's it.