Mick79's avatar

For the love of my sanity - HELP (POSTing checklist values from a form)

I feel like I could bang a brick off of my head for not being able to understand this.

I have a form that contains a checklist and I only want to pass through the checked values to my controller (obviously). Can I get it to work? No! It seems to pass through all values, even those not checked. Please PLEASE help.

My Blade:

 @foreach($tracks as $track)

    <div class="col-12 col-sm-12">
        <div class="row">
            <div class="col-12 col-sm-12">
                <div class="cbx-row">
                    <input class="hidden-xs-up" type="checkbox" name="trackid[{{$loop->index}}]"
                           value="{{$track->id}}">
                    <input class="hidden-xs-up" type="hidden" name="trackname[{{$loop->index}}]"
                           value="{{$track->track}}">
                    <input type='hidden' name='tracksource[{{$loop->index}}]'value='{{$track->tracksource}}'>
                    <p>{{$track->track}}</p>

                </div>
            </div>
        </div>
    </div>

@endforeach

My Controller

$tracks = $request;
            foreach ($tracks as $track)
            {
                Track::create([
                    'user_id'      => $user->id,
                    'track_id'     => $track->trackid,
                    'track_source' => $track->tracksource,
                    'track_name'   => $track->trackname,
                    'token'        => $token,
                ]);
            }
0 likes
2 replies
Cronix's avatar
Cronix
Best Answer
Level 67

Sure, because you're iterating over everything in $request ($tracks = $request;), instead of just the array(s) you sent. I can help a bit...but you'll have to fill in where $user and $token is coming from since you don't show it in your code (only show using them but not where it comes from)

$tracks = $request->trackid;  //is an array containing only checked values
$tracknames = $reqeust->trackname; // is an array
$tracksources = $request->tracksource; // is an array

foreach ($tracks as $key => $trackId) {
    Track::create([
        'user_id'  => $user->id,
        'track_id' => $trackId,
        'track_source' => $tracksources[$key],
        'track_name' => $tracknames[$key],
        'token' => $token,
    ]);
}
1 like
Mick79's avatar

You're a lifesaver man! I'm so annoyed that I couldn't make that work. Compared to the rest of this app, It's a simple thing.

Thank you!

Please or to participate in this conversation.