Search code examples
formslaravelcheckboxdefault

In Laravel using the old helper, how to check value of old('value', 'default') when 'value' is an array and 'default' is a basic value?


Say I have checkboxes. Each with a value that goes into the array when checked.

<input type="checkbox" id="card_type1" name="card_type[]" value="easy" @if(old('card_type') != NULL && in_array('easy', old('card_type')) || old('foo', $parkingLot->m_plots_can_easycard) === '1') checked @endif>
<input type="checkbox" id="card_type2" name="card_type[]" value="icash" @if(old('card_type') != NULL && in_array('icash', old('card_type')) || old('foo', $parkingLot->m_plots_can_icash20) === '1') checked @endif>
<input type="checkbox" id="card_type3" name="card_type[]" value="ipass" @if(old('card_type') != NULL && in_array('ipass', old('card_type')) || old('foo', $parkingLot->m_plots_can_ipass) === '1') checked @endif>

Upon loading my form first time, I want to reflect the database value. If a value in the DB is '1', check the checkbox. I then modify the checkboxes - checking some and unchecking some - and submit the form and say the form submission fails. I then want to reflect the old values by checking whether each value is in the old checkbox array, checking the checkboxes if so.

My problem is that old('value', 'default') consists of both 'value' and 'default' and I can't really use separate methods to determine whether the checkbox should be checked. And if I do (as in above), then I can't just have old('default') - and do a separate check there - because having one parameter makes it old('value').

I'm not sure how to go about it in my situation. Any pointers or help would be much appreciated. I hope I illustrated clear enough what my situation is.


Solution

  • You may try the following

    <input type="checkbox" id="card_type1" name="card_type[]" value="easy" 
        @if (in_array('easy', old('card_type', [$parkingLot->m_plots_can_easycard === '1' ? 'easy' : '']))) 
            checked 
        @endif>
    <input type="checkbox" id="card_type2" name="card_type[]" value="icash" 
        @if (in_array('icash', old('card_type', [$parkingLot->m_plots_can_icash20 === '1' ? 'icash' : '']))) 
            checked 
        @endif>
    <input type="checkbox" id="card_type3" name="card_type[]" value="ipass" 
        @if (in_array('ipass', old('card_type', [$parkingLot->m_plots_can_ipass === '1' ? 'ipass' : '']))) 
            checked 
        @endif>