2016-06-29 52 views
1

我正在進行遷移,我希望某些字段不能爲空。爲了方便起見,我將使用Laravel附帶的用戶遷移作爲示例。Eloquent在非空字段中保存沒有值

Schema::create('users', function (Blueprint $table) { 
    $table->increments('id'); 
    $table->string('name'); 
    $table->string('email')->unique(); 
    $table->string('password'); 
    $table->rememberToken(); 
    $table->timestamps(); 
}); 

無其田是nullables但如果我做:

$user = new User(); 
$user->save(); 
User::all(); 

它返回

Illuminate\Database\Eloquent\Collection {#639 
    all: [ 
     App\User {#640 
     id: "1", 
     name: "", 
     email: "", 
     created_at: "2016-06-29 15:51:01", 
     updated_at: "2016-06-29 15:51:01", 
     }, 
    ], 
    } 

在哪裏)可空點(修正,如果我能救記錄,而不數據在非空字段?

回答

3

嗯,它們是空的,但它們不是空的 - 正如預期的那樣。爲了避免您必須使用驗證規則來強制執行空條目:

在控制器:

public function store(Request $request) 
{ 
    $this->validate($request, [ 
     'name' => 'required|min:4', 
     'email' => 'required|email', 
     'password' => 'required|min:8', 
    ]); 

    $user = User::create($request->only('name', 'email', 'password')); 

    return redirect()->route('users.show', $user->id); 
} 
1

我認爲VARCHAR領域有默認值是「」。 stringBlueprint $table生成varcharcolumn

如果你想設置沒有空列使用->nullable(false)

Schema::create('users', function (Blueprint $table) { 
    $table->increments('id'); 
    $table->string('name')->nullable(false); 
    $table->string('email')->unique()->nullable(false); 
    $table->string('password')->nullable(false); 
    $table->rememberToken(); 
    $table->timestamps(); 
}); 
相關問題