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>
Shankar Thiyagaraajan
  • 1,705
  • 4
  • 28
  • 46

4 Answers4

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.

Udo E.
  • 2,665
  • 2
  • 21
  • 33
  • 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. – James Aug 19 '19 at 09:56
  • spot on, worked on me! `[+1]` – kapitan Feb 24 '23 at 12:56
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.

Shankar Thiyagaraajan
  • 1,705
  • 4
  • 28
  • 46
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!

KevinY
  • 1,229
  • 1
  • 12
  • 27
0

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

Udo E.
  • 2,665
  • 2
  • 21
  • 33
ujwal dhakal
  • 2,289
  • 2
  • 30
  • 50