laravel 5 csrf_token value is Empty
Asked Answered
H

4

5

Why laravel 5 csrf_token value is empty always ?

How can i get that token value ?

I tried,

  {!! csrf_token !!} , {{ csrf_token }} and 
  {{ Form::open() }} ....{{ Form::close() }}

MY OUTPUT

  <input type="hidden" name="_token"></input>
Halle answered 5/2, 2016 at 5:1 Comment(1)
Do you use the web middleware when your form is created?Crumb
S
13

It's because you're not using the web group middleware. Laravel is smart enough to know that if you're not using that group a token is not necessary.

Try moving your route inside the Route::group(['middleware' => 'web'] ... and tell us about it :)

Source: I made the same mistake not too long ago.

Schoenberg answered 5/2, 2016 at 5:32 Comment(2)
This is the correct answer. Just fort anyone else who experience this, check that if you are using a file seperate to web.php (in my example a multi tenanted system that uses routes.php files for each tenant in addition to web.php for core routes) if your form is generated in a catch all route at the bottom of the routes.php file you are best off wrapping these routes inside the web middleware as well. Hopefully that makes sense just saying be aware of catch all routes causing this issue as well as it caught me out for a bit.Irairacund
spot on, worked on me! [+1]Hastings
H
2

Thanks to all.

Finally i find solution.

On Fresh Install:

Route::get('foo', function () {
  return csrf_token(); // null
});

Use this:

Route::group(['middleware' => 'web'], function () {
  Route::get('bar', function () {
    return csrf_token(); // works
});

});

Its Working.

Halle answered 5/2, 2016 at 5:46 Comment(0)
M
1

I stumbled across this post having spent the afternoon suddenly experiencing "The page has expired due to inactivity. " when I POSTed. When doing a "view source" all tokens were present and correct. It was only that I had included:

  $("#editaddTarget input").each(function () {
                    $(this).val("");

                });

That got fired when I launched a modal. So I learned something today and will not get back the 5 hours it took me to find this newbie clanger!

Mattoid answered 29/12, 2017 at 16:30 Comment(0)
B
0

Try echo Form::token();? If it doesn't work, try using php artisan generate:key on the console.

Brumaire answered 5/2, 2016 at 5:26 Comment(3)
This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - From ReviewCenturial
he is in problem with empty csrf so generating key would help manBrumaire
He already accepted an answer, you suggest him to try something - that should be a comment.Centurial

© 2022 - 2024 — McMap. All rights reserved.