viiskis
viiskis

Reputation: 164

Laravel checkbox with old inputs and default value not working as it should

I'm making an edit page which has checkboxes and I want that laravel would remember old inputs. I store in database 1 or 0 values for a specific option.

@foreach( $options['tuning'] as $key => $option)
    <div class="col-3 rent-car-security">
        <input type="checkbox" name="{{ $option }}" id="{{ $option }}"
               value="1" {{ old($option, $car->tuning_options->{ $option }) ? 'checked' : '' }}>
        <label for="{{ $option }}">{{ $key }}</label>
    </div>
@endforeach

Controller

private $tuning_options = [
  'Made for racing' => 'made_for_racing',
  'Increased engine power' => 'increased_engine_power'
];
------------
$options = [
  'tuning' => $this->tuning_options
];

return view('cars.edit', compact(['car', 'options']));

Form works correctly if option was 0 in the begining

Upvotes: 3

Views: 869

Answers (2)

viiskis
viiskis

Reputation: 164

I've added a hidden input and now it works perfectly

<input type="hidden" name="{{ $option }}" value="0">

Upvotes: 0

CodeBoyCode
CodeBoyCode

Reputation: 2267

The way I do it is to pluck the selected options from the database and turn them into an array, example below:

controller (edit method):

public function edit($id) {
    $options = Options::all();
    $selected_options = $options->pluck('id')->toArray()

    return view('example.view', compact('selected_options')); 
}

and then in my view I would do the following logic:

@foreach( $options['tuning'] as $key => $option)
    <div class="col-3 rent-car-security">
        <input type="checkbox" name="{{ $option }}" id="{{ $option }}" value="1" {{ in_array($option, $selected_options) ? 'selected' : '' }}>
        <label for="{{ $option }}">{{ $key }}</label>
    </div>
@endforeach

I hope that helps, let me know. This is based on the limited code that you supplied, and is purely an example to get you started - if you provide more I'd be happy to help you solve the problem completely

Upvotes: 3

Related Questions