如何在 Laravel 中创建新用户?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25970458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create new user in Laravel?
提问by user1692333
I created the model:
我创建了模型:
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class ClientModel extends Eloquent implements UserInterface, RemindableInterface {
protected $connection = 'local_db';
protected $table = 'administrators';
protected $fillable = ['user_id'];
public function getAuthIdentifier()
{
return $this->username;
}
public function getAuthPassword()
{
return $this->password;
}
public function getRememberToken()
{
return $this->remember_token;
}
public function setRememberToken($value)
{
$this->remember_token = $value;
}
public function getRememberTokenName()
{
return 'remember_token';
}
public function getReminderEmail()
{
return $this->email;
}
}
When I try to use it like this:
当我尝试像这样使用它时:
ClientModel::create(array(
'username' => 'first_user',
'password' => Hash::make('123456'),
'email' => '[email protected]'
));
It creates empty entry in DB...
它在数据库中创建空条目...
采纳答案by The Alpha
You are using create
method (Mass Assignment) so it's not working because you have this:
您正在使用create
方法(批量分配),因此它不起作用,因为您有这个:
// Only user_id is allowed to insert by create method
protected $fillable = ['user_id'];
Put this in your model instead of $fillable
:
把它放在你的模型中而不是$fillable
:
// Allow any field to be inserted
protected $guarded = [];
Also you may use the alternative:
您也可以使用替代方法:
protected $fillable = ['username', 'password', 'email'];
Read more about Mass Assignmenton Laravel
website. While this may solve the issue but be aware of it. You may use this approach instead:
在网站上阅读有关批量分配的更多信息Laravel
。虽然这可能会解决问题,但请注意。您可以改用这种方法:
$user = new User;
$user->username = 'jhondoe';
// Set other fields ...
$user->save();
回答by Marcin Nabia?ek
I think you make it too complicated. There is no need to make it this way. By default you have User
model created and you should be able simple to create user this way:
我觉得你说的太复杂了。没有必要这样做。默认情况下,您已经User
创建了模型,您应该可以通过这种方式简单地创建用户:
$user = new User();
$user->username = 'something';
$user->password = Hash::make('userpassword');
$user->email = '[email protected]';
$user->save();
Maybe you wanted to achieve something more but I don't understand what you use so many methods here if you don't modify input or output here.
也许你想实现更多的东西,但我不明白如果你在这里不修改输入或输出,你在这里使用这么多方法是什么。