15-5
用 fillable 批量賦值寫入
- 另一種更簡單的方式是改用 fillable 批量賦值(Mass Assignment)寫法
public function store(Request $request)
{
Cart::create([
'user_id' => $request->user()->id,
'product_id' => $request->product_id,
'amount' => $request->amount,
]);
return [];
}
-
接著到 /專案/app/Cart.php
設定哪些欄位可以使用 fillable
class Cart extends Model
{
protected $fillable = [
'user_id', 'product_id', 'amount',
];
...略...
}
- 若是有欄位因為資安或其他問題,不想讓它使用批量賦值,那請用 guarded 屬性,例如:
protected $guarded = [
'id', 'password',
];
- 批量賦值詳情可參考:https://learnku.com/docs/laravel/5.8/eloquent/3931#mass-assignment