0

I have multiple select box with same name inside loop in a form. I have added laravel validation to check select box selected or not. But validation error message is showing for all the select boxes. Please check image attached. Any help would be appreciated.

cart.blade.php

@forelse($carts as $key => $cart)
<div class="col-sm-4 col-sm-4-booking1 form-group {{ $errors->has('guest.*.sleeps') ? ' has-error' : '' }}">
    <label>Sleep(s)</label>

    <select class="form-control form-control-booking1 jsBookCalSleep"  name="guest[{{ $cart->_id }}][sleeps]">
    <option value="">Choose Sleep(s)</option>
    @for($i = 1; $i <= 30; $i++)
       <option value="{{ $i }}" @if($i == $cart->sleeps) selected @endif>{{ $i }}</option>
    @endfor
    </select>

    @if ($errors->has('guest.*.sleeps'))
         <span class="help-block"><strong>{{ $errors->first('guest.*.sleeps') }}</strong></span>
    @endif
</div> 
@empty
  <p>No bookings in your cart</p>
@endforelse

CartController.php

public function store(CartRequest $request)
{
    dd($request->all());
}

CartRequest.php

public function rules()
    {
        return [
            'guest.*.sleeps' => 'required|not_in:0'
        ];
    }

enter image description here

2 Answers 2

1

Try these

@php
 $inputName='guest.'.$cart->_id.'.sleeps';
@endphp
@if ($errors->has($inputName))
     <span class="help-block"><strong>{{ $errors->first($inputName) }}</strong></span>
@endif

I didn't tested it, If not working let me know

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. It is working. But small change (curley braces removed) from $inputName='guest.'.$cart->_id.'.sleeps';
Glad to hear it helped
0

Solution: We can solve this issue by using two function. a.collect and b. contains. See the example below.

<select class="form-control m-bootstrap-select m_selectpicker"
                                                name="generic_ids[]" data-live-search="true" multiple>
                                            <option value="">Select Generic</option>
                                            @foreach($generics as $generic)
                                                <option value="{{$generic->id}}"
                                                    @if(collect(app()->request->generic_ids)->contains($generic->id))
                                                    selected
                                                    @endif
                                                >{{$generic->title}}</option>
                                            @endforeach
                                        </select>

Code

Code Image

Output Outout image

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.