2014-09-22 136 views
2

我創建的模型:如何在Laravel中創建新用戶?

<?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; 
    } 
} 

當我嘗試使用這樣的:

ClientModel::create(array(
    'username' => 'first_user', 
    'password' => Hash::make('123456'), 
    'email' => '[email protected]' 
)); 

它創造了DB空項...

enter image description here

回答

1

你是使用create方法(質量分配),所以它不工作,因爲你有這個:

// Only user_id is allowed to insert by create method 
protected $fillable = ['user_id']; 

在你的模型將這個代替$fillable

// Allow any field to be inserted 
protected $guarde = []; 

您也可以使用替代:

protected $fillable = ['username', 'password', 'email']; 

閱讀Laravel網站更多Mass Assignment。雖然這可能會解決這個問題,但要意識到這一點。你也可以用這種方法代替:

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

我覺得你讓它太複雜了。沒有必要這樣做。默認情況下,你已經User模型創建的,你應該能夠簡單的創建用戶這樣說:

$user = new User(); 
$user->username = 'something'; 
$user->password = Hash::make('userpassword'); 
$user->email = '[email protected]'; 
$user->save(); 

也許你想實現更多的東西,但我不明白,你用什麼這麼多的方法,在這裏,如果你不」在此修改輸入或輸出。