'How to use Laravel Accessor in Laravel Validation
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
