0

I'm trying to build Laravel project that will have a multi-select dropdown with list of categories. Selecting category should reload the page and apply filter. "scopeFilter" in my model is actually doing filtering, but here i just need to find a way to properly form URL. The problem is that this code i have:

<form id="cats-form" action="#" method="GET">
<select multiple class="chosen-select" name="test[]">
    @foreach($categories->get() as $cat) //this loop goes through existing categories in the system
        @php
            //if category is part of URL, pre-select it in the select:
            $arr = request()->all();
            $selected = '';
            if(array_key_exists('test', $arr)) {
                $testArr = $arr['test'];
                $selected = in_array($cat->id, explode(',', $testArr)) ? 'selected' : '';
            }
        @endphp
        <option {{ $selected }} value="{{ $cat->id }}">{{ $cat->name }}</option>
    @endforeach
</select>
</form>

    <script>
        $(".chosen-select").chosen({ })
    
        $('.chosen-select').on('change', function(evt, params) {
            $('#cats-form').submit();
        });
    </script>

Is actually giving me this URL:

http://localhost:11089/?test%5B%5D=19&test%5B%5D=5

While i actually need this:

http://localhost:11089/?test=19,5

I guess it's a trivial problem to solve for someone with better knowledge of Laravel, can you tell me pls what i'm doing wrong here?

guest86
  • 2,894
  • 8
  • 49
  • 72

1 Answers1

0

This is rather how the language or framework or library reads an URL query string. Assuming that your prefered way of URL string is a valid format (as I usually see the format ?arr[]=val1&arr[]=val2 and never see the second format that you preferred), both query string formats should be acceptable to PHP.

As Yarin stated that the best way PHP reads an array is the first method, you don't have to worry too much because the decoded URL query string is exactly in the first format.

Elvis
  • 73
  • 8
  • It turns out Laravel 8 understands url perfectly and doing "request()->all()["test"]" would return the data i needed in form of an array :) – guest86 Mar 15 '22 at 01:01
  • You may also use the query() function of an request object to retrieve input from query string. See: https://laravel.com/docs/8.x/requests#retrieving-input – Elvis Mar 15 '22 at 04:01