zwl1619
zwl1619

Reputation: 4232

How to show old data of dynamic checkbox in Laravel?

I am using Laravel 5.3,this is a form demo below:

<div class="container">
    <form>
        <div class="form-group row">
            <label for="name" class="col-sm-2 col-form-label">Name</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" id="name" name="name" value="{{ old('name', $student->name)}}">
            </div>
        </div>

        <fieldset class="form-group row">
            <legend class="col-form-legend col-sm-2">Gender</legend>
            <div class="col-sm-10">
                <div class="form-check">
                    <label class="form-check-label">
                        <input class="form-check-input" type="radio" name="gender" value="1" @if(old('gender',$student->gender)=="1") checked @endif>
                        Male
                    </label>
                </div>
                <div class="form-check">
                    <label class="form-check-label">
                        <input class="form-check-input" type="radio" name="gender" value="2" @if(old('gender',$student->gender)=="2") checked @endif>
                        Female
                    </label>
                </div>
            </div>
        </fieldset>
        <div class="form-group row">
            <label class="col-sm-2">Hobbies</label>
            <div class="col-sm-10">
                <div class="form-check">
                    <label class="form-check-inline">
                        <input class="form-check-input" type="checkbox" name="hobby[]" value="1" @if(...) checked @endif> football
                    </label>
                    <label class="form-check-inline">
                        <input class="form-check-input" type="checkbox" name="hobby[]" value="2" @if(...) checked @endif> basketball
                    </label>
                    <label class="form-check-inline">
                        <input class="form-check-input" type="checkbox" name="hobby[]" value="3" @if(...) checked @endif> swimming
                    </label>
                </div>

            </div>
        </div>
        <div class="form-group row">
            <div class="offset-sm-2 col-sm-10">
                <button type="submit" class="btn btn-primary">Submit</button>
            </div>
        </div>
    </form>
</div>

My question is:

I can show old data in input type="text" like this:

<input type="text" class="form-control" id="name" name="name" value="{{ old('name', $student->name)}}">

And I can show old data in input type="radio" like this:

<input class="form-check-input" type="radio" name="gender" value="1" @if(old('gender',$student->gender)=="1") checked @endif>

But I don't know how to show old data in input type="checkbox":

<input class="form-check-input" type="checkbox" name="hobby[]" value="3" @if(...) checked @endif>

How to do it?

Upvotes: 25

Views: 62310

Answers (10)

Mark Neale
Mark Neale

Reputation: 1

This snippet uses an array of Timesheet models and I want to be able to select a set of these using checkboxes. The tickbox should be initially ticked if the value of sales_invoice_id is not null. Note that I set indexes on my array because this makes it much easier to analyse the POST data later.

@foreach ($timesheets as $ts)
  <input type="checkbox" name="ts_id[{{$ts->id}}]" value="1"
      @if (array_key_exists($ts->id, old('ts_id', ($ts->sales_invoice_id != null) ? [$ts->id => 1] : [] )))
         checked
      @endif
  >
@endforeach

This works by pulling the "old" array of timesheet checkboxes and looking to see if the timesheet we are looking at is in the list using array_key_exists() However the first time the form is displayed there is no "old" session data so the 2nd parameter to old() provides the default value. The default value is set to an array of 1 item if the checkbox should be ticked, or an empty array if not.

Upvotes: 0

Mehravish Temkar
Mehravish Temkar

Reputation: 4365

Update for Laravel 9.x as Yusuf T suggested (refer this document) :

<input type="checkbox" name="active" value="active" @checked(old('active', $someVariableOrValue )) />

For older versions this will work:

<div class="form-check">
    <label class="form-check-inline">
        <input class="form-check-input" type="checkbox" name="hobby[]" value="1" @if(is_array(old('hobby')) && in_array(1, old('hobby'))) checked @endif> football
    </label>
    <label class="form-check-inline">
        <input class="form-check-input" type="checkbox" name="hobby[]" value="2" @if(is_array(old('hobby')) && in_array(2, old('hobby'))) checked @endif> basketball
    </label>
    <label class="form-check-inline">
        <input class="form-check-input" type="checkbox" name="hobby[]" value="3" @if(is_array(old('hobby')) && in_array(3, old('hobby'))) checked @endif> swimming
    </label>
</div>

Also as brokekidweb suggested :

<label class="form-check-inline">
    <input class="form-check-input" type="checkbox" name="hobby[]" value="1" {{ (is_array(old('hobby')) and in_array(1, old('hobby'))) ? ' checked' : '' }}> football
</label>

OR

<label class="form-check-inline">
    <input class="form-check-input" type="checkbox" name="hobby[]" value="1" {{ (is_array(old('hobby')) && in_array(1, old('hobby'))) ? ' checked' : '' }}> football
</label>

Upvotes: 87

Levi
Levi

Reputation: 69

My solution:

<input type="checkbox" class="custom-control-input" name="hobby" value="1"
   @if((old('_token') && old('hobby') != null) || (old('_token') == null && $employee->hobby))
   checked 
   @endif
>

Upvotes: 2

SHAKIL DHANGA
SHAKIL DHANGA

Reputation: 21

Try this:

$hobby = explode(', ', $data->hobby);

<input class="form-control" name="hobby[]" type="checkbox" value="cricket" <?=(in_array('cricket',$hobby) ? 'checked="checked"' : '')?>> 

Upvotes: 0

Lipa
Lipa

Reputation: 51

Use flash data (Laravel Flash Data) to set the information for Blade about checked/unchecked checkbox.

My example: checkbox "legal" which should be accepted.

In Controller:

  1. Put checkbox in validator

    'legal'  => 'required|accepted'
    
  2. After validator set flash data:

    $request->session()->flash('legal', 'true');
    

In Blade:

<input class="form-check-input" type="checkbox" name="legal"
id="legal" {{Session::has('legal') ? 'checked' :''}}

Upvotes: 1

Kabir Safi
Kabir Safi

Reputation: 87

@

foreach($brands as $key => $brand)
                             <label class="container col-sm-3">{!! $brand->name !!}
                                    <input type="checkbox" class="brand_id" id="brand_id" name="brand_id[]"
                                     value="{{@(!empty($brand->id) ? $brand->id : "")}}"
                                    @foreach($brand_sel as $key => $_sel)
                                     {{($brand->id == $_sel->brand_id ? "checked='checked'": '')}}
                                    @endforeach()
                                     />
                                    <span class="checkmark"></span>
                                </label>
                            @endforeach()

Upvotes: -1

Mart
Mart

Reputation: 61

These all appear to work, a cleaner solution that I adopt takes the form of the following...

<input type="checkbox" name="departments[]" value="{{ $item->id }}" {{ in_array($item->id, old('departments', [])) ? 'checked' : '' }}>

Where $item is the object while iterating over a collection,

Rather than explicitly checking if we have an array, we can defer the default value of the old value as being an array in the instance the form has yet to be submitted or there were no options checked on the original form request.

Referring back to OPs original query, it could be structured similar to the below

<input class="form-check-input" type="checkbox" name="hobby[]" value="1" {{ in_array(1, old('hobby', [])) ? 'checked' : '' }}>

Upvotes: 4

Muhammad Umar
Muhammad Umar

Reputation: 105

1st WAY

First create variable

$hob = old('hobby');

and than check is array or not

echo is_array($hob) ? (in_array(1, $hob)?'checked':NULL) : NULL;

and then apply it.

<input class="form-check-input" type="checkbox" name="hobby[]" value="1" <?php echo is_array($hob) ? (in_array(1, $hob)?'checked':NULL) : NULL; ?>> football

2nd WAY

OR you can do that but in this case you will not create variable

@if(is_array(old('hobby')) && in_array(1,old('hobby'))) checked @endif

and then apply it.

<input class="form-check-input" type="checkbox" name="hobby[]" value="1" @if(is_array(old('hobby')) && in_array(1,old('hobby'))) checked @endif > football

Upvotes: 5

Senthil
Senthil

Reputation: 2246

Had to iterate through the $userHobbies array to pull out just the ID for each item then in the view changed the Form::checkbox to:

{{ Form::checkbox('hobby[]', $user->hobby, in_array($user->hobby, $hobbiesAvailableIds)) }}

Ref: http://laravel.io/forum/09-15-2014-how-to-show-checkboxes-as-checked-when-values-are-set-in-the-database

Upvotes: 1

Nestor Mata Cuthbert
Nestor Mata Cuthbert

Reputation: 1359

You can use

<input class="form-check-input" type="checkbox" name="hobby[]" value="3" @if(in_array(3, old('hobby'))) checked @endif>

Or you could just switch to use Laravel Collective https://laravelcollective.com/docs/5.3/html#checkboxes-and-radio-buttons

And have code like this instead:

{!! Form::checkbox('name', 'value', true) !!}

Upvotes: 6

Related Questions