javascriptjquerylaravel

open route .show when onchange a dropdown


In my view tests.index is it possible to open my route tests.show by clicking in a select dropdown where datas comes from database ?

My controller :

public function index(Request $request)
{ 
  $tests = DB::table('test')->distinct()->get();
  return view('tests.index')->with('tests', $tests);
}

public function show($id)
{ 
  $test = Test::findOrFail($id); 
  return view('tests.show', compact('test')); 
}

My view index :

 <select id="apports" type="dropdown-toggle" class="form-control" name="apports" onchange="{{ route("tests.show", $test->id) }}">
<option value="choisir" selected disabled>Choisir</option>
@foreach($tests as $test)
<option class="apports" value="{{$test->id}}">{{$test->apports}}</option>
@endforeach

When I put my route here : onchange I get the error "Undefined variable: test" when I add a button below the select like that :

<a class="btn btn-small btn-success" href="{{ route("tests.show", $test->id) }}">Show</a>

I get always the last id of the table...

I would prefer not have a button, just when I change value in the select, return tests.show... Is someone could help me please ?


Solution

  • All you need is a javascript snippet to read the select option change and redirect you.

    <select id="apports" type="dropdown-toggle" class="form-control" name="apports">
        <option value="choisir" selected disabled>Choisir</option>
        @foreach($tests as $test)
            <option class="apports" value="{{ route("tests.show", $test->id) }}">{{ $test->apports }}</option>
        @endforeach
    </select>
    
    <script>
        $('select').on('change', function (e) {
            var link = $("option:selected", this).val();
            if (link) {
                location.href = link;
            }
        });
    </script>