2016-05-13 98 views
1

當有人在我正在構建的應用程序中創建一個帳戶時,他們必須提供一個國家/地區。Laravel 5.2 - 自定義表單字段名稱和驗證

爲了向用戶提供可供選擇的國家列表,有一個countries表,其中有兩個字段:idcountry_codeusers表具有country_id字段。

我想用一個名爲country代替country_id一個選擇框,但我無法找出我將如何實現這一目標。任何想法?當然,驗證和東西仍然必須工作。

另外,是否必須在驗證碼中指定countries.id的精確字段?現在,我有這樣的:

$this->validate($request, [ 
    'name' => 'required', 
    'country_id' => 'required|exists:countries,id' 
]); 

至於說,屬性名應該是country代替country_id,但因爲我已經指定了用戶和國家模型之間的雄辯關係,做這樣'required|exists:countries'事情應該做的把戲,對吧?

回答

2
<select name="country"> 
    <option value="1">US</option> 
    <option value="2">UK</option> 
</select> 

和驗證

$this->validate($request, [ 
    'country' => 'required|integer|exists:countries,id' 
]); 

country == name attribute countries == table name

So it will check the value from selected option(id) with existing id in countries table 

如果國家與選定的ID表國家存在保存用戶

$user = New User; 
$user->country_id = $request->input('country'); 
$user->save(); 

Laravel驗證不會將數據庫中的列與您的輸入名稱綁定 我還會在exists之前添加integer驗證

+0

這比我預期的要容易得多。我使用'$ request-> merge(['country_id'=> $ request-> input('country')]);'所以我可以使用'$ user-> create($ request-> all()); 。謝謝! –

+0

@ Willem-Aart yeap)) 但是要小心,在你的'Model'中設置'$ guarded或$ fillable array'的列,以便只填充你允許閱讀的數據https://laravel.com/docs/5.1 /雄辯#大規模分配 – Froxz