laravel 5.5 The page has expired due to inactivity. Please refresh and try again

I'm new with Laravel and I have a problem which I don't understand. I have а log form in my project and my method is POST. When I try a request the result is:

'The page has expired due to inactivity. Please refresh and try again.'

But if I change the method to GET, It works fine.

Can someone tell me why is that and how to fix it? because of course I need POST method.


Solution 1:

This problem comes from the CSRF token verification which fails. So either you're not posting one or you're posting an incorrect one.

The reason it works for GET is that for a GET route in Laravel, there is no CSRF token posted.

You can either post a CSRF token in your form by calling:

{{ csrf_field() }}

Or exclude your route (NOT RECOMMENDED DUE TO SECURITY) in app/Http/Middleware/VerifyCsrfToken.php:

protected $except = [
    'your/route'
];

Solution 2:

In my case, I've got the same error message and then figured out that I've missed to add csrf_token for the form field. Then add the csrf_token.

Using form helper that will be,

{{ csrf_field() }}

Or without form helper that will be,

<input type="hidden" name="_token" value="{{ csrf_token() }}">

If that doesn't work, then-

Refresh the browser cache

and now it might work, thanks.

Update For Laravel 5.6

Laravel integrates new @csrf instead of {{ csrf_field() }}. That looks more nice now.

<form action="">
   @csrf
   ...
</form>

Solution 3:

Anytime you define an HTML form in your application, you should include a hidden CSRF token field in the form so that the CSRF protection middleware can validate the request. You may use the csrf_field helper to generate the token field:

<form method="POST" action="/profile">
    {{ csrf_field() }}
    ...
</form>

It doesn't work, then Refresh the browser cache and now it might work,

For more details open link :- CSRF Protection in Laravel 5.5

UPDATE:

With Laravel 5.6 using Blades templates, it's pretty easy.

<form method="POST" action="/profile">
    @csrf
    ...
</form>

For more details open link :- CSRF Protection in Laravel 5.6