Pass value of select to route in Laravel

Asked

Viewed 1,569 times

0

I don’t know much about web development and I’m a little lost. I need to pass the id of a movie to a route in Laravel and I’m not sure how to get this value.

<select class="form-control" style="width: 20%"  onchange="" id="select" name="filme">
  <option value="" selected disabled>Selecione um filme</option>
    @foreach($filmes as $f)
      <option value="{{$f->id}}">{{$f->nome}}</option>
    @endforeach
</select>
<?php echo $var = pegaId(); ?>
<br><br>
  <button type="submit" class="w3-btn-block" onclick="window.location='/filmes/{{$var}}'">Ver eventos</button>

<script type="text/javascript">
  function pegaId(){
    return document.getElementById('select');
  }
</script>

I read that there is no way to assign the return of a JS function to a php variable because Javascript runs on the client side and PHP on the server side, so my variable does not recognize the return of the function at that time. That’s right?

When I call the function pegaId() of the error

Call to Undefined Function pegaId()

I believe I have an easier way to do this, like calling the JS function in my url but I’m not getting it :(

  • Where does the information come from? is from array de $filmes? why what you did seems almost right but, {{$var}} comes from where?

  • is below select, I try to make a call to pegaId() function but error Call to undefined function pegaId()

1 answer

1


I think what you want is something like:

View:

<form class="form-horizontal" role="form" method="POST" action="{{ route('selecionar.filme') }}">
{{csrf_field() }}

<select class="form-control" style="width: 20%"  onchange="" id="select" name="filme">
  <option value="" selected disabled>Selecione um filme</option>
    @foreach($filmes as $f)
      <option value="{{$f->id}}">{{$f->nome}}</option>
    @endforeach
</select>

<br><br>
  <button type="submit" class="w3-btn-block">Ver eventos</button>
</form>

Route:

Route::post('selecionarFilme', ["as" => 'selecionar.filme', 'uses' => "FilmeController@store"]);

Controller:

public function store(Request $request)
{
        $selecao = $request->get('select');

        return redirect('filmes/'.$selecao);
}
  • Just one question: the call FilmeController@selecionar Are you right? Wouldn’t it be FilmeController@store? And what’s being done on that line dd($selecao)

  • The method name is "indifferent", but of course you can use the store name :)

  • I beg your pardon, since the method I’ve laid out is called store will have to be FilmeController@store. Or change the method name to select

  • I did not understand how I can use the return of the store function and redirect to the page filmes/{{$var}}. I want the user to be redirected to this page by clicking the button

  • I edited the answer in order to answer that question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.