Skip to content

Instantly share code, notes, and snippets.

@jimgwhit
Last active June 6, 2022 19:12
Show Gist options
  • Save jimgwhit/3c1026871ca4246d6ae9f71012ba8e4d to your computer and use it in GitHub Desktop.
Save jimgwhit/3c1026871ca4246d6ae9f71012ba8e4d to your computer and use it in GitHub Desktop.
Checkbox array

First, in html if a checkbox is not checked nothing is passed for that checkbox in the request.

For example if you had a form with name and likes, (pick from the following)

Name  ________________

I like:

biking __
jogging __ 
swimming __ 
baseball __

Where the __ would be checkboxes on the form

Now if Rob checks biking, jogging, and baseball you would get in the request the following array:

array:3 [▼
  0 => "biking"
  1 => "jogging"
  2 => "baseball"
]

Notice swimming is not there, he did not check it.

You can json_encode the array and store it in db. And latter loop it if on an edit page and refill what was checked from the database.

However I like storing all 4 choices by filling the empty with null and store:

["biking", "jogging", null, "baseball"]

In the create method:

// Top I use facade also, so I have:

use Illuminate\Http\Request as Req;

    public function create(Req $request) {
        $request->validate([
            'myname' => 'required'
        ]);

        $name = Request::input('myname');
        if (Request::has('likes')) {
            $postedarray = Request::input('likes');
	    // array of all possible choices
            $comparearray = ["biking", "jogging", "swimming", "baseball"];
            $storearray = [];

            foreach ($comparearray as $k => $v) {
                if (in_array($v, $postedarray)) {
                    $storearray[] = $v;
                } else {
                    $storearray[] = null;
                }
            }
            $myjson = json_encode($storearray);
        } else {
            $storearray = [null, null, null, null];
            $myjson = json_encode($storearray);
        }

        $postdata = array(
            'name' => $name,
            'likes' => $myjson   // stored as json
        );

        DB::table('mylikes')->insert($postdata);
    }

The create form:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Untitled Document</title>
    </head>

    <body>
        <form action="create" method="post">
            <?php echo csrf_field(); ?>
            <br>
        @if ($errors->any())
            <div class="alert alert-danger">
                <ul>
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        
            <input type="text" name="myname" id="myname" value=""><br>
            
            I like: <br>
            @foreach ($knownarray as $k => $v)
                {{ $v }} : <input type="checkbox" name="likes[]" value="{{ $v }}"{{ ( is_array(old('likes')) && in_array($v, old('likes')) ) ? 'checked ' : '' }}  /><br>

            @endforeach
        @else
        
            <input type="text" name="myname" id="myname" value=""><br>
            I like: <br>
                @foreach ($knownarray as $k => $v)
                    {{ $v }} : <input type="checkbox" name="likes[]" value="{{ $v }}"  /><br>
                @endforeach                
        @endif
            <input type="submit" value="Submit!"/>
        </form>

    </body>
</html>

Notice if validation fails you have old data.

For an edit view:

@extends('layouts.edittp')
@section('content')
<div style="margin-right:auto;margin-left:0px; width:400px;">
    <form action='update' method='post'>
        <input type='hidden' name='id' value="{{ $mylikes->id }}">
        <?php echo csrf_field(); ?>
                
        @if ($errors->any())
            <div class="alert alert-danger">
                <ul>
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
            <input type="text" name="myname" id="myname" value="{{ $mylikes->name }}"><br><br>
            @foreach ($knownarray as $k => $v)

                {{ $v }} : <input type="checkbox" name="likes[]" value="{{ $v }}"{{ ( is_array(old('likes')) && in_array($v, old('likes')) ) ? 'checked ' : '' }}  /><br>

            @endforeach
        @else
            <input type="text" name="myname" id="myname" value="{{ $mylikes->name }}"><br><br>
                @foreach ($knownarray as $k => $v)
                    {{ $v }} : <input type="checkbox" name="likes[]" value="{{ $v }}" {{ in_array($v, $storedarray) ? 'checked' : ''}} {{ ( is_array(old('likes')) && in_array($v, old('likes')) ) ? 'checked ' : '' }}  /><br>
                @endforeach                
        
        
        @endif
        <p><input type='submit' name='submit' value='Update'></p>

    </form></div>
<br>

@endsection

The error section is to show old data, otherwise it's showing stored data from database.

The update method is similar to create, you compare to known values.

@JohnBisson
Copy link

Newbie here. I want to make a 3row 10-15 column checkbox array. Your work looks promising, but I only know PHP and SQL. Is there a place where I could see a more complete example?

Thanks,

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment