Xavier Issac
Xavier Issac

Reputation: 495

Laravel Checkboxes are not getting checked based on daatabse value

Hi in my laravel project i have set of locations and set of services (Both are seperate tables).In each location various services are offering which can be set by user. My requiremnt is that i want to make my checkboxes selected based on database value

Following is my code in view

<div class="form-group">
       <label class="control-label">Services
           <star>*</star>
            </label> <br>
    @foreach($services as $service)
    <input type="checkbox" name="service[]" id="service" value="{!! $service->serviceID !!}">{!! $service->serviceName !!}<br>
    @endforeach
   @if ($errors->has('service')) <span class="help-block"> {{ $errors->first('service') }} </span> @endif 
   </div>

What is wrong in my code.Kindly help

Upvotes: 0

Views: 340

Answers (2)

Luca Puddu
Luca Puddu

Reputation: 501

@foreach($services as $service)
    <label for="service_{{$service->serviceID}}">
    <input type="checkbox" name="service[]"
           @if($service->someField == 'someValue') checked @endif
           id="service_{{$service->serviceID}}"
           value="{{$service->serviceID}}">
@endforeach

You need to add the checked property to the input when a condition is met (e.g. $service->someField == 'someValue').

Also, each input should have a different id. Use some unique property of the service to generate the id dynamically (e.g. serviceID).

Upvotes: 0

Akhzar Javed
Akhzar Javed

Reputation: 628

You need to add checked attribute on checkbox input field

Example:

<input {{ $service->serviceID == DatabaseValue ? 'checked' : '' }} type="checkbox" name="service[]" id="service" value="{!! $service->serviceID !!}">{!! $service->serviceName !!}>

Place your database value at DatabaseValue & it will compare and apply checked attribute base on condition

Upvotes: 1

Related Questions