Search code examples
validationlaravel-5error-messaging

How to return validated value of ID in Laravel validation


So I have created looped generated radio-buttons:

<div class="custom-control custom-radio guest-form">
    @foreach(config('const.res_site') as $id => $res)
    <div class="form-radio">
        <input class="custom-control-input" type="radio" onchange="otherResSite({{$id}})" id="{{$res}}" value="{{$id}}" 
            name="reservation_site" {{ old("reservation_site") == $id ? "checked" : "" }}>
        <label for="{{ $res }}" class="custom-control-label">{{ $res }}</label>
    </div>
    @endforeach
    <div class="otherField" id="ifOtherSite" class="otherSite" style="display: {{ old('reservation_site') == 4 ? 'display:inline-flex' : 'none' }}">
        <input type='text' class="form-control" id='otherSite' name='otherSite' value="{{ old('otherSite', '') }}"><br>
    </div>
</div>
@if ($errors->has('otherSite'))
    <div class="form-group">
        <p class="text-danger">{{ $errors->first('otherSite') }}</p>
    </div>
@endif

const.php

'res_site' => [
    0 => 'site1',
    1 => 'site2',
    2 => 'other',
],

This one is to validate the otherSite value if selected option is other. It now works well but the validation message returned is like this:

The other site field is required when reservation site is 2.

My validator is like this:

return [
    'reservation_site' => ['required'],
    'otherSite' => ['required_if:reservation_site,2'],
]

Now, how can I make its return message as

The other site field is required when reservation site is other

Is there any way I can do that?


Solution

  • Okay. If someone might need this someday, I did it this way:

     <input class="custom-control-input" type="radio" id="{{$res}}" value='{{$id == 4 ? "other" : $id}}'>
    

    and in my validation:

    return [
            'reservation_site' => ['required'],
            'otherSite' => ['required_if:reservation_site,other'],
    ]