Non Brazilian Non Brazilian - 7 months ago 21
PHP Question

Php laravel TokenMismatchException request

am try to send request by post form from but error TokenMismatchException

here is my controller code

public function postSaveedit(Request $request) {
$var1 = $request->input('title'); //name on the form
$var2 = $request->input('meaning'); //name on the form
$words = User::where("title", $var1)->update(array("meaning" => $var2));

return view('dict.watch', compact('words'));
}


here is view code.

<form class="form-horizontal" role="form" method="POST" action="{{ URL::to('index/saveedit') }}">
<div class="form-group">
<label class="col-lg-3 control-label">Title:</label>
<div class="col-lg-8">
<input class="form-control" value='{{ $words->first()->title }}' type="text" name="title">
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Meaning:</label>
<div class="col-lg-8">
<input class="form-control" value="{{ $words->first()->meaning }}" type="text" name="meaning">
</div>
</div>

<div class="form-group">
<label class="col-md-3 control-label"></label>
<div class="col-md-8">
<input class="btn btn-primary" value="Save Changes" type="submit">
<span></span>

</div>
</div>
</form>


thnak you for your help

Answer

Laravel automatically generates a CSRF "token" for each active user session managed by the application. This token is used to verify that the authenticated user is the one actually making the requests to the application.

Anytime you define a HTML form in your application, you should include a hidden CSRF token field in the form so that the CSRF protection middleware will be able to validate the request. To generate a hidden input field _token containing the CSRF token, you may use the csrf_field helper function

Just add this line inside your form

<form class="form-horizontal" role="form" method="POST" action="{{ URL::to('index/saveedit') }}">
     <input type="hidden" name="_token" value="{{ csrf_token(); }}">
    <div class="form-group">
      <label class="col-lg-3 control-label">Title:</label>
      <div class="col-lg-8">
        <input class="form-control" value='{{ $words->first()->title }}' type="text" name="title">
      </div>
    </div>
    <div class="form-group">
      <label class="col-lg-3 control-label">Meaning:</label>
      <div class="col-lg-8">
        <input class="form-control" value="{{ $words->first()->meaning }}" type="text" name="meaning">
      </div>
    </div>

    <div class="form-group">
      <label class="col-md-3 control-label"></label>
      <div class="col-md-8">
        <input class="btn btn-primary" value="Save Changes" type="submit">
        <span></span>

      </div>
    </div>
  </form>