Система голосования Laravel получает номер проекта, который выбирает пользователь

я делаю систему голосования с помощью laravel framework, но теперь я столкнулся с проблемой. Я хочу передать номер проекта, выбранный пользователями, в другое представление (все под одним и тем же контроллером). В другом проекте я использовал Input::get(), но теперь что-то не работает. Я получаю MethodNotAllowedHttpException в строке RouteCollection.php 218: Вот моя часть представления projecs_list,

`

 @foreach($project as $key => $value) `
    <form class="form-horizontal" role="form" method="POST" action="{{ url('/vote'}}" >
        <div class="row banner">

            <div class="col-md-8 col-md-offset-2 ">

                <div class="project_nr_5" name="5" >
                <h3 class="text-primary text-center">
                 {{ $value->tytuł}}
                </h3>
                <p class="lead">
                {{ $value->opis}}
                </p>
                <p class="lead">
                {{ $value->lokalizacja }}
                </p>
                <p name="project_id" id="project_id">  Projekt numer: {{ $value->id}} </p>
                <button type="submit"   value=" {{ $value->id }} " class="btn btn-primary center-block" >
                ZAGŁOSUJ
              </button>
                </a>
                </div>
            </div>

            </div>
        </form>
        @endforeach

отсюда я хотел бы передать значение project_id.

Вот маршруты

`

Route::get('/projekty','MakeVoteController@show_projects');
Route::get('/vote','MakeVoteController@index');
Route::post('/store','MakeVoteController@store');
`
`

Вот контроллер

`

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Voter;
use App\Vote;
use App\SingleProject;
use Illuminate\Support\Facades\Input;
class MakeVoteController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
         //$project_id = Input::get('project_id');

        //number of the projet the user choosed
      $selected_project = Input::get('project_id');
      return view('vote')
        ->with('selected_project', $selected_project);

    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        // Save data to table Voters, get values from submit of vote form

       // $data= Input::all();


        $this->validate($request, [
            'pesel' =>'required|unique|max:11|min:11',
            'name' =>'required|max:64|min:2',
            'surname' => 'required|max:128|min:2'
            ]);

        $newvoter = new Voter;
        $newvoter->name = Input::get("name");
        $newvoter->surname = Input::get("surname");
        $newvoter->pesel = Input::get("pesel");
        $newvoter->save();

        $givevote = new Vote;





        return "Successfull adding to database";



    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {

    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    public function show_projects()
    {
      $projects = SingleProject::all();

        return view('projects_list')
            ->with('project', $projects);
        $proj_select_id = Input::get("project_id");
        index($proj_select_id);
    }



}

`

и, наконец, вот окно голосования, где пользователь заполняет форму и голосует за выбранный проект.

`

<div class="panel panel-default">
                <div class="panel-heading"> Zagłosuj na projekt nr {{ $selected_project }}</div>
                <div class="panel-body">
                    <form class="form-horizontal" role="form" method="POST" action="{{ url('/store') }}">

                    {{ csrf_field() }}

                    <div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
                        <label for="name" class="col-md-4 control-label">Imie</label>
                        <div class="col-md6">
                            <input id="name" maxlength="255" type="text" class="form-control" name="name" required autofocus>
                            @if ($errors->has('name'))
                                <span class='help-block'>
                                    <strong>{{ $errors->first('name') }}</strong>
                                </span>
                            @endif
                        </div>
                    </div>

                    <div class="form-group{{ $errors->has('surname') ? ' has-error' : '' }}">
                            <label for="surname"class="col-md-4 control-label">Nazwisko</label>
                            <div class="col-md6">
                                <input id="surname" type="text" class="form-control" name="surname" required>

                                @if ($errors->has('surname'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('surname') }} </strong>
                                    </span>
                                @endif
                            </div>
                      </div>
                      <div class="form-group{{ $errors->has('pesel') ? ' has-error' : '' }}">
                            <label for="pesel"class="col-md-4 control-label">pesel</label>
                            <div class="col-md6">
                                <input id="pesel" type="text" class="form-control" name="pesel" required maxlength="11" minlength="11">

                                @if ($errors->has('pesel'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('pesel') }} </strong>
                                    </span>
                                @endif
                            </div>
                        </div>
                        <div class="form-group{{ $errors->has('street') ? ' has-error' : '' }}">
                            <label for="street"class="col-md-4 control-label">Ulica</label>
                            <div class="col-md6">
                                <input id="street" type="text" class="form-control" name="street" required >

                                @if ($errors->has('pesel'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('pesel') }} </strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                     <div class="form-group">
                            <div class="col-md-6 col-md-offset-4">
                                <button type="submit" class="btn btn-primary">
                                    Zagłosuj
                                </button>
                            </div>
                        </div>
                        </div>

                    </form>
                </div>

person Wini the Pooh    schedule 25.11.2016    source источник
comment
Укажите, пожалуйста, где находится строка 218.   -  person Carcigenicate    schedule 26.11.2016
comment
Строка RouteCollection: 218 защищена function methodNotAllowed(массив $others) { throw new MethodNotAllowedHttpException($others); }   -  person Wini the Pooh    schedule 26.11.2016
comment
Пожалуйста, включите это и код вокруг него в вопрос.   -  person Carcigenicate    schedule 26.11.2016


Ответы (1)


В представлении project_list вы определяете атрибут формы method="POST" action="{{ url('/vote'}}"

Но в вашем маршруте вы определяете /vote с помощью http GET метода: Route::get('/vote','MakeVoteController@index');

Они должны быть в одном и том же методе http.

person Dharma Saputra    schedule 25.11.2016
comment
В зависимости от того, нажимаю ли я на href (тогда я получаю TokenMismatchException) или записываю вручную (localhost/vote здесь, я получаю MethodNotAllowed...) - person Wini the Pooh; 26.11.2016
comment
добавьте {{ csrf_field() }} в форму project_list, если вы хотите использовать метод POST. - person Dharma Saputra; 26.11.2016
comment
К сожалению, пока ничего. Я добавил {{ csrd_field() }} непосредственно перед формой, но все равно получаю исключение TokenMismatchException - person Wini the Pooh; 26.11.2016
comment
Хорошо, когда я изменил маршрут /vote с поста на get, я обычно могу перейти в localhost/view, но это все еще не решает мою проблему с передачей значения. Или, может быть, я мог бы сделать это по-другому? - person Wini the Pooh; 26.11.2016