简体   繁体   English

如何在 Laravel 中创建新用户?

[英]How to create new user in Laravel?

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'    => 'my@email.com'
));

It creates empty entry in DB...它在数据库中创建空条目...

在此处输入图片说明

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 = 'useremail@something.com';
$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.也许你想实现更多的东西,但我不明白如果你在这里不修改输入或输出,你在这里使用这么多方法是什么。

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 Assignment on Laravel website.Laravel网站上阅读更多关于批量分配的信息。 While this may solve the issue but be aware of it.虽然这可能会解决问题,但请注意。 You may use this approach instead:您可以改用这种方法:

$user = new User;
$user->username = 'jhondoe';
// Set other fields ...
$user->save();

Nowadays way :现在的方式:

User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);

or even:甚至:

        $arrLcl = [];
        $arrLcl['name'] = $data['name'];
        $arrLcl['email'] = $data['email'];
        $arrLcl['password'] = $data['password'];
        User::create($arrLcl);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM