我學習Laravel
,當我通過artisan tinker
試圖將用戶與下面的代碼無法創建通過MassAssignment的新模式,使QueryException重複條目
$user = App\User::create([
'username'=>'johnd',
'first_name'=>'john',
'last_name'=>'doe',
'email'=>'[email protected]',
'password'=>'thisShouldBeRandom',
'shool_id'=>1,'type'=>'TEACHER'
]);
它拋出這個錯誤:
Illuminate\Database\QueryException with message 'SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'username' (SQL: insert into `users` (`first_name`, `last_name`, `type`, `updated_at`, `created_at`) values (john, doe, TEACHER, 2015-12-22 07:12:49, 2015-12-22 07:12:49))'
我的模特是:
namespace App;
use App\School;
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\Access\Authorizable;
use League\Flysystem\Exception;
use URL;
class User extends Model implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['school_id', 'type'];
/**
* The attributes that are NOT mass assignable.
*
* @var array
*/
protected $guarded = ['email', 'password', 'username'];
}
另外我注意到它的錯誤當我還將username
包括在數組中時,只試圖將以下列插入first_name
,last_name
,type
,updated_at
,created_at
。我錯過了什麼?
編輯
看來我不得不在
再次感謝所有的幫助!username, email
添加和在
fillable
屬性字段的休息,但我想這可能會使它
unsecure
,因爲它是從請求可填寫。我認爲這對公共數據比如文章,帖子,評論等更合適。我想我會用一種不同的方法來處理敏感數據,但我可能會錯誤。
P.S.使用artisan tinker
進行測試時,請確保關閉實例並在修改代碼時重新啓動,因爲它會保留舊的編譯實例並且看不到您的更改。花了我一段時間才意識到並引起了很多頭痛。
但是,您爲什麼認爲發送用戶名是不安全的?我們已經知道我們發送的所有內容都是不安全的,除非您使用的是htpps連接。 – Amarnasan
@Amarnasan文檔中的這條語句'當一個用戶通過一個請求傳遞一個意外的HTTP參數,並且該參數改變了您沒有想到的數據庫中的一列時,會發生一個羣集分配漏洞。 '或者我誤解了它? – JohnnyQ
但是,只有當你盲目地將整個輸入數組設置爲更新參數時纔會發生這種情況。 – Amarnasan