I am learning Routing
in Laravel 5.4
by viewing a tutorial created by DevDojo
. Using the following codes in routes/web.php
will emerge the TokenMismatchException
error and my code does not work after I press the submit button:
Route::post('test', function () {
return 'Printed by the route responsible for test post action.';
});
Route::get('test', function () {
echo '<form method="post" action="test">';
echo '<input type="submit">';
echo '</form>';
});
I searched this same forum here and also the other places on the net like laravel.io
or laracasts.com
and everyone is talking about problems that occur when Laravel tries to detect the session
of the request that is getting made.
I tried to fix the problem by adding the following lines to the Route::get
rules but the issue does not get fixed:
echo '<input type="hidden" name="_method" value="post">';
echo '<input type="hidden" name="_token" value="csrf_field();">';
I hope you help me fix it by telling me how to properly use csrf_field()
, csrf_token()
or anything else needed here in the route file.
Thank you very much in advance.
csrf_token()
just gives you the token.
csrf_field()
builds the entire input field for you.
example:
{{ csrf_token() }}
// Outputs: SomeRandomString
{{ csrf_field() }}
// Outputs: <input type="hidden" name="_token" value="SomeRandomString">
in your question: use
<input type="hidden" name="_token" value="csrf_token();">;
instead of
<input type="hidden" name="_token" value="csrf_field();">;
on the other hand
you could use
echo csrf_field();
OR
{{ csrf_field() }}