:::
9-4 用 fillable 批量賦值寫入
- 另一種更簡單的方式是改用 fillable 批量賦值(Mass Assignment)寫法
public function store(Request $request) { Exam::create([ 'title' => $request->title, 'user_id' => $request->user_id, 'enable' => $request->enable, ]); return redirect()->route('exam.index'); } -
接著到
/專案/app/Exam.php設定哪些欄位可以使用 fillableclass Exam extends Model { protected $fillable = [ 'title', 'user_id', 'enable', ]; } - 由於
enable是boolean類型,但在資料庫卻被存成數字,所以,需要做一下型別轉換,因此,我們利用$casts來進行型別轉換。關於型別轉換,可參考:https://laravel-china.org/docs/laravel/5.6/eloquent-mutators/1406#attribute-castingprotected $casts = [ 'enable' => 'boolean', ]; - 若是有欄位因為資安或其他問題,不想讓它使用批量賦值,那請用 guarded 屬性,例如:
protected $guarded = [ 'id', 'password', ]; - 批量賦值詳情可參考:https://laravel-china.org/docs/laravel/5.6/eloquent/1403#c7d398
二、更簡易的寫法
- 也可以用
$request->all()取得使用者填寫的所有資料陣列public function store(Request $request) { Exam::create($request->all()); return redirect()->route('exam.index'); } -
完工!

-
關於 Request 的詳情可以查看:https://laravel-china.org/docs/laravel/5.6/requests/
9-3 將資料寫進資料庫
