In Laravel-8 I have this unique rules request validation:
public function rules()
{
return [
//company
'companyName' => [
'required',
'string',
'min:3',
'max:100',
],
'country_id' => [
'nullable',
],
];
}
How do I make companyName unique in relation to country_id?
Thanks
You can create a custom validation rule for your set of rules.
I'm suggesting that your Country
has hasMany()
relationship to Company
public function rules()
{
return [
//company
'companyName' => [
'required',
'string',
'min:3',
'max:100',
function($attribute, $value, $fail) {
$country = Country::findOrFail(request()->get('country_id'));
if(!$country->companies()->whereName(request()->get('companyName'))->get()->isEmpty()) {
$fail('Woops, there\'s a country with this name. Type another one, please :)');
}
},
],
'country_id' => [
'nullable',
],
];
}
Read more about Custom Laravel Validation Rules here: https://laravel.com/docs/8.x/validation#custom-validation-rules