I want to filter the product based on user clicked checkbox. I want to append the checkbox value and show it in URL and filter products based on those value in URL. I used onChange="this.form.submit()"
but everytime i check the checkbox it replaces old value with new in URL. How to append all these values and filter based on those values.
<form action="{{route('filter')}}" method="GET"
>
<div class="container">
<div class="row">
<div class="col-md-4">
Search
<input type="checkbox" name="category_id['samsung']" class="form-control" value="1" onChange="this.form.submit(){{ request()->filled('category_id.samsung') ? 'checked' :''}}">Samsung
<input type="checkbox" name="category_id['android']" class="form-control" value="2"onChange="this.form.submit(){{ request()->filled('category_id.android') ? 'checked' :''}}" >Android
<input type="checkbox" name="category_id['apple']" class="form-control" value="3" onChange="this.form.submit(){{ request()->filled('category_id.apple') ? 'checked' :''}}">Apple
</div>
</form>
my url is browser is:
http://localhost:8000/?category_id%5B%27samsung%27%5D=1
http://localhost:8000/?category_id%5B%27android%27%5D=2
http://localhost:8000/?category_id%5B%27apple%27%5D=3
the value is url is updated when i checked another checkbox, actually i need to append it
As was suggested in the comments, use category_id[]
as the name attribute for each input. Then the URL becomes http://localhost:8000/?category_id[]=1
.
The problem remains that on every page load the checkboxes are cleared. Pre-selecting them can be done with these conditions:
is_array(request()->input('category_id')) &&
in_array('1', request()->input('category_id')) ? 'checked' : ''
Now it is possible to filter on multiple items, and the URL becomes like this:
http://localhost:8000/?category_id[]=1&category_id[]=2
Here is a full solution:
<form action="{{ route('filter') }}" method="GET">
<div class="container">
<div class="row">
<div class="col-md-4">
Search
<input type="checkbox" name="category_id[]" class="form-control" value="1" onChange="this.form.submit()" {{ is_array(request()->input('category_id')) && in_array('1', request()->input('category_id')) ? 'checked' : ''}}>Samsung
<input type="checkbox" name="category_id[]" class="form-control" value="2" onChange="this.form.submit()" {{ is_array(request()->input('category_id')) && in_array('2', request()->input('category_id')) ? 'checked' : ''}}>Android
<input type="checkbox" name="category_id[]" class="form-control" value="3" onChange="this.form.submit()" {{ is_array(request()->input('category_id')) && in_array('3', request()->input('category_id')) ? 'checked' : ''}}>Apple
</div>
</div>
</div>
</form>