Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

laravel

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

like image 624
viiskis Avatar asked Dec 05 '25 16:12

viiskis


1 Answers

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

like image 182
CodeBoyCode Avatar answered Dec 08 '25 08:12

CodeBoyCode



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!