如何在 Laravel 验证中使用 Laravel Accessor
我想在验证中使用 laravel 访问器,但我没有找到正确的方法来做到这一点 我的模型(每个国家/地区一种货币)
class Currency extends Model
{
protected $table = 'currency';
protected $fillable = [
'code', 'country_id'
];
public function country()
{
return $this->belongsTo(Country::class);
}
public function getCountryCodeAttribute()
{
return $this->country->alpha_2;
}
}
形式示例
<input type="text" name="code">
<select name="country">
<option value="" disabled selected>Choose your option</option>
<option value="FR">France</option>
<option value="PT">Portugal</option>
<option value="ES">Spain</option>
</select>
在我的控制器中我尝试了这个
public function addCurrency(Request $request){
$validator = Validator::make($request->all() , [
'code' => 'required|string' ,
'country' => ['required', 'exists:country,alpha_2', Rule::unique('currency', 'country.alpha_2') ],
]);
if ($validator->fails()) {
return response()->json([
'errors' => $validator->errors(),
]) ;
}
}
以及这个
public function addCurrency(Request $request){
$validator = Validator::make($request->all() , [
'code' => 'required|string' ,
'country' => ['required', 'exists:country,alpha_2', Rule::unique('currency', 'country_code') ],
]);
if ($validator->fails()) {
return response()->json([
'errors' => $validator->errors(),
]) ;
}
}
但没有工作
PS:我不想使用 alpha_2 作为外键而不是country_id 我不想在表单的值选项中使用country_id
I want to use laravel accessor in validation but i didn't figure the right way to do this
my model (one currency for each country)
class Currency extends Model
{
protected $table = 'currency';
protected $fillable = [
'code', 'country_id'
];
public function country()
{
return $this->belongsTo(Country::class);
}
public function getCountryCodeAttribute()
{
return $this->country->alpha_2;
}
}
example of the form
<input type="text" name="code">
<select name="country">
<option value="" disabled selected>Choose your option</option>
<option value="FR">France</option>
<option value="PT">Portugal</option>
<option value="ES">Spain</option>
</select>
In my controller i tried this
public function addCurrency(Request $request){
$validator = Validator::make($request->all() , [
'code' => 'required|string' ,
'country' => ['required', 'exists:country,alpha_2', Rule::unique('currency', 'country.alpha_2') ],
]);
if ($validator->fails()) {
return response()->json([
'errors' => $validator->errors(),
]) ;
}
}
and also this
public function addCurrency(Request $request){
$validator = Validator::make($request->all() , [
'code' => 'required|string' ,
'country' => ['required', 'exists:country,alpha_2', Rule::unique('currency', 'country_code') ],
]);
if ($validator->fails()) {
return response()->json([
'errors' => $validator->errors(),
]) ;
}
}
but didn't work
PS: i don't want to use the alpha_2 as the foreign key instead of country_id
and i don't want to use country_id in the value options in form
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论