2016-05-13 60 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