新定義 Laravel Model中的_schema() method
參考資料 :
https://vocus.cc/article/5ff66eb9fd897800018728b3
前言 :
為什麼要這樣做? Laravel的Model並沒有_schema()這個method,完全是我們開發團隊自行定義出來的
原因如下
-
為了統一在Model中描述每個欄位的資料該如何被驗證
-
滿足Model中的fillable欄位描述
會這樣子做就是因為我們發現在Model中本來就需要描述一次filleble,而在資料寫入的controller中又需要在描述一次所有欄位的驗證內容
因此把欄位名稱當成key,驗證資料當成value寫在_schema() method中
像這樣
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php namespace App\Models; class Customer extends Model { protected $table = 'customer'; public function _schema(): array { return [ 'name' => 'required|string|max:60', 'address' => 'required|string|max:60', 'status' => 'required|boolean' ]; } } |
這樣一來,我們只要在controller中這樣做,就可以直接取得驗證資料
1 2 3 |
public function create(Request $request){ $payload = $request->validate((new Customer)->_schema()); } |
而在原本的Customer model中你應該會發現其實並沒有描述fillable的部分,實際上是因為在Customer繼承的Model中我們已經做過處理
1 2 3 4 5 6 7 8 |
abstract class Model extends BaseModel { public function __construct(array $attributes = []) { $this->fillable = array_keys($this->_schema()); parent::__construct($attributes); } } |
因此每個繼承這個Model的Model Class只需要描述好_schema() method就可以啦