166

I installed Laravel 5.7

Added a form to the file \resources\views\welcome.blade.php

<form method="POST" action="/foo" >
    @csrf
    <input type="text" name="name"/><br/>
    <input type="submit" value="Add"/>
</form>

Added to file \routes\web.php

Route::post('/foo', function () {
    echo 1;
    return;
});

After sending a POST request:

419 Sorry, your session has expired. Please refresh and try again.

In version 5.6 there was no such a problem.

Shobi
  • 10,374
  • 6
  • 46
  • 82
  • Have you tried adding a redirect? Instead of `return;` you can call `return redirect()->back();`. From what I can see, the app has nothing to do after the post request. Maybe you can redirect it to a view after processing the request. – dcangulo Oct 01 '18 at 02:57
  • 1
    I'm having the same issue. When i switch to database session this happens and when i change back to `file` for `SESSION_DRIVER` in `.env` it works fine. Why is the database based session not working. – Junaid Qadir Shekhanzai Nov 05 '18 at 11:14
  • I copied your exact code into a fresh laravel 5.7 install. It worked. There is a problem elsewhere. – Kyle Wardle Nov 06 '18 at 11:37
  • this problem because of token problem. I have try to run same code like this, but get no error. You should give more information like your session driver, _token value display in the form. Also, you can debug yourself in this file `vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php` line 67 to know why – bangnokia Nov 06 '18 at 18:37
  • 1
    I realized that I had used `sessions` table for a different purpose. After Changing this table name to a more suited one and ran `artisan session:table` and refreshed migration everything is working fine – Junaid Qadir Shekhanzai Nov 07 '18 at 05:35
  • I tested your code and found no problem. It showed no warning message and echos 1 accurately. I am also using laravel 5.7 – Md. Harun Or Rashid Nov 09 '18 at 08:29
  • Sessions are supposed to expire, so just to check the obvious question - how long was the form open for before you submitted it? What is the value of `lifetime` in `config/session.php`? – Don't Panic Nov 11 '18 at 11:03
  • Since the OP author didn't chime in and tell what solved his problem. I see a lot of solutions here which didn't solve the issue I had. I solved it differently, so no one answer is correct I guess. All of them may be correct in different scenarios. Hence I hold my bounty offer. – Junaid Qadir Shekhanzai Nov 13 '18 at 06:19
  • You can add an answer which solved your problem unless its referenced in any answers here (because it doesn't make sense). And according to you which answer you have liked the most/more suitable for future OP's you can award the bounty. because you can't get the bounty points back at any circumstances – Shobi Nov 13 '18 at 07:33
  • [if you will need to exclude your response route from CSRF protection](https://stackoverflow.com/questions/48339630/remove-csrf-token-only-for-single-method-laravel/54652249#54652249) – mohamed elshazly Feb 12 '19 at 14:34
  • https://stackoverflow.com/questions/37806762/how-to-disable-csrf-token-in-laravel-and-why-we-have-to-disable-it – Sahal Nov 03 '20 at 11:24
  • After trying every clear commands (optimize:clear, route:clear etc ) i run "php artisan config:cache" Then it fixed the issue for 419 page expired on live server. – Braham Dev Yadav Oct 12 '22 at 10:59
  • always include csrf data in your html header like this `````` and include another in your form via ```@csrf```. Use developer inspection view on the browser to check if they both match and you don't have some javascript messing up the CSRF data in the form (as was my case). It's a good place to start troubleshooting. – Udo E. Jul 10 '23 at 08:51

56 Answers56

247

Before reading below make sure you have @csrf or {{ csrf_field() }} in your form like

<form method="post">
@csrf <!-- {{ csrf_field() }} -->
... rest of form ...
</form>

The Session Expired or 419 Page Expired error message in Laravel comes up because somewhere your csrf token verification fails which means the App\Http\Middleware\VerifyCsrfToken::class middleware is already turned on. In the form the @csrf blade directive is already added, which should be fine as well.

Then the other area to check is the session. The csrf token verification is directly involved with your session, So you might want to check whether your session driver is working or not, such as an incorrectly configured Redis might cause an issue.

Maybe you can try switching your session driver/software from your .env file, the supported drivers are given below

Supported Session drivers in Laravel 5, Laravel 6 and Laravel 7 (Doc Link)

  • file - sessions are stored in storage/framework/sessions.
  • cookie - sessions are stored in secure, encrypted cookies.
  • database - sessions are stored in a relational database.
  • memcached / redis - sessions are stored in one of these fast, cache based stores.
  • array - sessions are stored in a PHP array and will not be persisted.

If your form works after switching the session driver, then something wrong is with that particular driver, try to fix the error from there.

Possible error-prone scenarios

  • Probably file-based sessions might not work because of the permission issues with the /storage directory (a quick googling will fetch you the solution), also remember putting 777 for the directory is never the solution.

  • In the case of the database driver, your DB connection might be wrong, or the sessions table might not exist or wrongly configured (the wrong configuration part was confirmed to be an issue as per the comment by @Junaid Qadir).

  • redis/memcached configuration is wrong or is being manipulated by some other piece of code in the system at the same time.

It might be a good idea to execute php artisan key:generate and generate a new app key which will, in turn, flush the session data.

Clear Browser Cache HARD, I found Chrome and Firefox being a culprit more than I can remember.

Read more about why application keys are important

Tiago Martins Peres
  • 14,289
  • 18
  • 86
  • 145
Shobi
  • 10,374
  • 6
  • 46
  • 82
  • 4
    Sometimes it's just that browsers, mainly Chrome won't put the Set-Cookie session value because it's malformed or non-standard. So Laravel won't find any existing session value from the HTTP request to compare to the received `_token` value from the FORM. Avoid using `SESSION_DOMAIN=...` with IP which Chrome and [HTTP Cookie Specs](https://tools.ietf.org/html/rfc2109#section-4.3.2) consider as insecure. – KeitelDOG Dec 07 '18 at 15:54
  • 4
    I have the same problem, but I do not recieve the error constantly. It just occures from time to time. I guess that means there's no problem with the session driver, because it works 99% of the time. But I'm running a live app and I get complaints from clients from time to time. It is very rare though. I am using the file session driver. Does someone know why this happens in my case? Thank you – Angel Miladinov Sep 11 '19 at 15:45
  • 1
    @TheAngelM97 You can easily reproduce this error by going to either the login or register page. Don't do anything for, maybe, more than 30 minutes. Then when you click on submit, the `419 Page Expired` shows up. For usability's sake, how do you tell a simple user what just has happened and how to solve it? – Pathros Jun 08 '20 at 16:55
  • What's the difference between using `@csrf` or `{{ csrf_field() }}`? Is it the same thing? – Will Kim Nov 19 '22 at 13:10
  • it is the same thing. just two ways of doing it. – Shobi Nov 21 '22 at 08:58
55

This is because the form requires a csrf. In version 5.7, they changed it to @csrf

<form action="" method="post">
    @csrf
    ...

Referene: https://laravel.com/docs/5.7/csrf

David
  • 826
  • 6
  • 4
32

case 1 : if you are running project in your local system like 127.0.01:8000 ,

then

add SESSION_DOMAIN= in your .env file

or in your config/session.php 'domain' => env('SESSION_DOMAIN', ''),

and then run php artisan cache:clear

case 2: if project is running on server and you have domain like "mydomain.com"

add SESSION_DOMAIN=mydomain.com in your .env file

or in your config/session.php 'domain' => env('SESSION_DOMAIN', 'mydomain.com'),

and then run php artisan cache:clear

Saurabh Mistry
  • 12,833
  • 5
  • 50
  • 71
12

How about using

{{ csrf_field() }} instead of @csrf

419 error is mostly because of csrf token issues.

Bonish Koirala
  • 641
  • 5
  • 16
11

I use Laravel 5.7 I had the same problem and it was because the csrf token wasn't in the form, so adding

@csrf

fixed the problem

Karim Samir
  • 1,470
  • 17
  • 17
11

It could be a problem with your session. After playing around with these settings I resolved my problem. For me it turned out to be the last option.

  • If you are using "file" as session driver look into storage/framework/sessions if the sessions are getting saved after a refresh. If not It is most likely due to incorrect folder permissions. Check that your storage/ folder have the correct right
  • Try to disable all the Javascript in your pages (either by disabling it via navigator or inside the code) and make sure that 'http_only' => true,
  • Try to use with and without https
  • Make sure the SESSION_DRIVER variable is NOT null
  • Try to switch between 'encrypt' => false, and 'encrypt' => true,
  • Try to change the cookie name 'cookie' => 'laravelsession',
  • Try either to set your SESSION_DOMAIN to your actual domain OR null
  • Try to switch between 'secure' => env('SESSION_SECURE_COOKIE', false), and 'secure' => env('SESSION_SECURE_COOKIE', true),

Source:Laravel Session always changes every refresh / request in Laravel 5.4

Bram Janssen
  • 1,057
  • 1
  • 9
  • 14
  • Yes, after try many other things, the `SESSION_SECURE_COOKIE` switch (changed it to `false`) did it for me. (on `localhost:8000`) – Marten Koetsier Nov 03 '19 at 12:56
  • SESSION_SECURE_COOKIE was also the problem for me, I it changed it when following a guide for website optimization. – Bram Janssen Nov 04 '19 at 17:12
  • for me it works with https but not with http... any idea why? thanks for the great answer, took me hours to find it. – sharkyenergy Apr 17 '20 at 07:39
11

It should work if you try all of these steps:

  1. Ensure that your session is well configured, the easiest way is to make it file and make sure storage folder has chmod 755 permission then in your .env you set it like below, file session driver is the easiest way to set.

    SESSION_DRIVER=file
    SESSION_DOMAIN=
    SESSION_SECURE_COOKIE=false
    
  2. Ensure Cache folder is cleared and writable, you can do this by running below artisan command.

    php artisan cache:clear
    
  3. Ensure folder permissions are well set, they should be configured like below:

    sudo chmod -R 755 storage
    sudo chmod -R 755 vendor
    sudo chmod -R 644 bootstrap/cache
    
  4. Ensure your form has @csrf token included.

Hope this will solve your problem.

Kamaro
  • 955
  • 1
  • 10
  • 11
9

419 | page this error means laravel security issue it means csrf token field is not used correctly.

use {{csrf_field}} and your issue will be solved.

Udhav Sarvaiya
  • 9,380
  • 13
  • 53
  • 64
Flutterer
  • 239
  • 2
  • 9
9

To solve this error you first need to insert one of the following commands into the form tag.

@csrf OR {{ csrf_field }}

If your problem is not resolved, do the following: (Note that one of the above commands must be in the form tag)

1.Insert one of the following commands into the form tag @csrf OR {{ csrf_field }}

2.Open the .env file and change the values ​​to the "file" in the SESSION_DRIVER section.

3.Then you should reset laravel cache. type below commands in the terminal

php artisan view:clear php artisan route:clear php artisan cache:clear

php artisan config:cache

4.In the final step, unplug the project from the serve and click again on php artisan serve

I hope your problem is resolved

hosein azimi
  • 321
  • 3
  • 5
8

Try to comment out \App\Http\Middleware\EncryptCookies::class in \app\Http\Kernel.php I have similar problem and solved it by doing so. Probably not the best solution because the security but at least it worked.

Previously I tried:

  • Clear cache
  • Generate new app key
  • Run my app in various Browsers (Chrome 70, Mozilla Firefox 57, and IE 11)
  • Run my app in another computer
  • Comment out \App\Http\Middleware\VerifyCsrfToken::class in \app\Http\Kernel.php
  • Comment out \Illuminate\Session\Middleware\AuthenticateSession::class in \app\Http\Kernel.php
  • Upgrade and downgrade Laravel (between 5.6 and 5.7)

But none of these above worked for me.

EDIT

My case here is every time I login, a new session file will be created (The old one is still persist, but suddenly forgotten. Check storage/framework/sessions) and new CSRF token is generated. So the problem is not with VerifyCsrfToken.

As @Vladd mentioned in comment section, you should never comment out \App\Http\Middleware\VerifyCsrfToken::class. You have to check that you sent the right CSRF TOKEN to the server.

Prasna Lukito
  • 97
  • 1
  • 6
  • 1
    Among those ways you mentioned, only commenting out \App\Http\Middleware\VerifyCsrfToken::class in \app\Http\Kernel.php worked for me. – Lex Soft Feb 21 '19 at 15:25
  • 1
    Clear cache, Generate new app key + Remove cookies – dobs Apr 01 '19 at 13:41
  • 2
    You never shall c0mmenting out \App\Http\Middleware\VerifyCsrfToken::class. Why would you do that? To create your self weak point in app? – Vladd May 23 '19 at 02:43
  • @dobs Thanks for adding '+ Remove Cookies' because I was getting a 419 error even after doing everything I possible could and it only worked when I cleared the browser cookies / tried in incognito. – Niraj Pandey Jul 03 '19 at 15:59
7

ob_start();

This problem take more than two days with me the solution was simple :

go to public folder and add this ob_start(); in first line in index.php

Important: after that clear cache of browser. you can follow this guide to clear your browser's cache

Abd Abughazaleh
  • 4,615
  • 3
  • 44
  • 53
  • amazingly it worked .. but could not get the reason ... it has been on my local docker but suddenly appeared 419 error on every request – For Guru Aug 14 '22 at 15:46
6

change your @csrf in welcome.blade.php to <input type="hidden" name="_token" value="{{ csrf_token() }}">

so your code like this:

<form method="POST" action="/foo" >
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
    <input type="text" name="name"/><br/>
    <input type="submit" value="Add"/>

   <button type="submit">Submit</button>
</form>
Aghnat Atqiya
  • 275
  • 5
  • 18
4

There is no issue in the code. I have checked with the same code as you have written with new installation.

Form Code:

<form method="POST" action="/foo" >
    @csrf
    <input type="text" name="name"/><br/>
    <input type="submit" value="Add"/>
</form>

web.php file code:

Route::get('/', function () {
    return view('welcome');
});

Route::post('/foo', function () {
    echo 1;
    return;
});

The result after submitting the form is: Output after submitting the form

If you clear your browser cache or try with other browser, I think it will fixed.

engrhussainahmad
  • 1,008
  • 10
  • 19
4

A quick bad approach is that go to app\http\middleware\verifycsrftoken.php and add the route in $except list. The post request will be ignord for CSRF Token verification.

protected $except = [
    //
    'doLogin.aspx',
    'create_coupon',
];
Qasim Ali
  • 787
  • 6
  • 17
4

Go to config/sessions.php

find the row

'secure' => env('SESSION_SECURE_COOKIE', true),

change it to false

'secure' => env('SESSION_SECURE_COOKIE', false),

If this parameter is set to TRUE browser will require you to use HTTPS protocol, otherwise it wont store the session. As it is not valid

Rafayel
  • 53
  • 1
  • 2
  • 8
4

Please also update CSRF in header

<meta name="csrf-token" content="{{ csrf_token() }}">

Update CSRF in Form

@CSRF

if you have already CSRF in header and Form then Go To config/session.php and update

'domain' => env('SESSION_DOMAIN', 'example.com'),[ Only Domain name without https ]
3

After so much time i got it solved this way

My laravel installation path was not the same as set in the config file session.php

'domain' => env('SESSION_DOMAIN', 'example.com'),
3

add csrf token and your issue will be solved . {{csrf_token}} or @csrf

samair ali
  • 772
  • 1
  • 5
  • 15
3

After many searches I found solution here,

Inside your main index.php file inside public folder, edit it and at the very top write ob_start()

2

It may be overkill but you can try this:

// Form calling named route with hidden token field added.

<form method="POST" action="{{ route('foo') }}" >
    @csrf
    <input type="hidden" name="_token" value="{!! csrf_token() !!}">
    <input type="text" name="name"/><br/>
    <input type="submit" value="Add"/>
</form>

// Named Route

Route::post('/foo', function () {
    return 'bar';
})->name('foo');

// Add this within the <head></head> block:

<meta name="_token" content="{!! csrf_token() !!}" />

I did test it on my local using Homestead on Laravel 5.7 which was was fresh install using Laravel Installer 2.0.1 and it worked. What is your environment?

Theory: I wonder if that has something to do with blade rendering html tags with {{ }} vs. {!! !!} on your environment or how you are serving it (eg. php artisan serve). What makes me think that is line 335 of /vendor/laravel/framework/src/illuminate/Foundation/helpers.php should render the same line manually typed out above.

jeremykenedy
  • 4,150
  • 1
  • 17
  • 25
2

If you already have the csrf directive, you might have changed the way sessions runs.

In config/session.php, check the 'secure' field. It should be on false if https isn't available on your server.

You can also put SESSION_SECURE_COOKIE=FALSE on your .env file (root directory).

Udhav Sarvaiya
  • 9,380
  • 13
  • 53
  • 64
Towelie
  • 69
  • 4
2

open command line cmd on your project.

1.command

php artisan config:cache

2.comand

php artisan route:clear
Biblbroks42
  • 330
  • 3
  • 11
2

While the form has @csrf, it still shows 419 pages has expired

I solved it after update SESSION_SECURE_COOKIE option to false in config/session.php

'secure' => env('SESSION_SECURE_COOKIE', false)

than clear cache

Kakada NEANG
  • 451
  • 1
  • 6
  • 16
2

I tried all the answers provided here. However none of them worked for me in shared hosting. However, soultion mentioned here works for me How to solve "CSRF Token Mismatch" in Laravel l

avinashkrc
  • 93
  • 1
  • 9
2

In my case was a missing ?> at the end of routes/web.php.

Tiago Martins Peres
  • 14,289
  • 18
  • 86
  • 145
Juan Angel
  • 656
  • 6
  • 6
2

2021, I faced this error while applying all above solutions, my every route was throwing 419. My app was working fine on localhost but 419 on server. Then I got solution while fixing .env file on production, remove sanctum variables from .env and set 'secure' => env('SESSION_SECURE_COOKIE', null) in config/session.php

Abid_niazi_15
  • 825
  • 8
  • 6
1

I just had the exact same issue and it was down to me being completely stupid. I had disabled all of the form fields (rather than just the submit button) via javascript before submitting said form! This, of course, resulted in the all the form elements not being submitted (including the hidden _token field) which in turn brought up the 419 error!

I hope this helps someone from a few hours of head scratching!

Disabled form inputs do not appear in the request

Splodge
  • 21
  • 5
1

In your Http/Kernel.php

try to comment this line :

\Illuminate\Session\Middleware\AuthenticateSession::class,

in your web middleware array

it might be the root of your issue

Mathieu Ferre
  • 4,246
  • 1
  • 14
  • 31
1

Actually CSRF is a session based token. Add your route in a route group and add a middleware which control the sessions.

web is a default middleware in laravel and it can controls the session requests.

Route::group(array('middleware' => ['web']), function () {
  Route::post('/foo', function () {
     echo 1;
     return;
  });
});
Udhav Sarvaiya
  • 9,380
  • 13
  • 53
  • 64
Zia
  • 213
  • 1
  • 8
1

In default I didn't have this problem. So what I did is chmod -R 644 sessions to replicate the problem.

enter image description here

Afterwards I gave permissions to sessions folder by chmod -R 755 sessions

now my project code works again.

enter image description here

Reason it happens is you store your cache on file with lack of writing permissions.

The session configuration file is stored at config/session.php. Be sure to review the options available to you in this file. By default, Laravel is configured to use the file session driver, which will work well for many applications. In production applications, you may consider using the memcached or redis drivers for even faster session performance.

Solutions:

1 - As I have fixed above you can give 755 permission to sessions folder. 2 - You can use another session driver configuration.

file - sessions are stored in storage/framework/sessions. cookie - sessions are stored in secure, encrypted cookies. database - sessions are stored in a relational database. memcached / redis - sessions are stored in one of these fast, cache based stores. array - sessions are stored in a PHP array and will not be persisted.

Bear in mind; If you want to use memcached/redis you need to have them installed on your server or your docker redis container must be running.

Anar Bayramov
  • 11,158
  • 5
  • 44
  • 64
1

Please note you get error 419 if you are trying to upload a big file that exceeds the post file size limit. In this case you can increase both upload_max_filesize and post_max_size to a reasonable amount, (e.g. 10M or 20M depends on your use case and resources), check here: https://stackoverflow.com/a/2184541/2100489

But this may cause resource consumption issues, e.g bandwidth and storage. As a solution you can check the file size before submitting the form and show a warning message.

Kiafar
  • 176
  • 2
  • 8
1

For me the error comes once the session become invalid and user tries to submit the post request. The csrf_token were no longer valid. so I overcomes it by changing the Handler.php in Exceptions directory and try catch the token mismatch exception like this.

The render function was like this

public function render($request, Exception $exception)
{
    return parent::render($request, $exception);
}

Then I modify it to look like this

public function render($request, Exception $exception)
{

    if ($exception instanceof \Illuminate\Session\TokenMismatchException){ // <<<=========== the Code
        if ($request->expectsJson()) {
            return response()->json(['error' => 'Unauthenticated.'], 401);
        }

        return redirect('/home')->with('message', 'You page session expired. Please try again');
    }
    return parent::render($request, $exception);
}

Simply you choose the route that can handle the token refresh operation.

Ruberandinda Patience
  • 3,435
  • 3
  • 20
  • 18
0

Add in your form on .blade.php file {{ csrf_field() }} or @csrf like this

<form method='POST' action='route("exampleRoute")'>
   {{ csrf_field() }} or @csrf
   ....
   ....
</form>
Biblbroks42
  • 330
  • 3
  • 11
0

Do you also have the csrf in the header of your application?

<meta name="csrf-token" content="{{ csrf_token() }}">
iranimij
  • 91
  • 10
0

I just went throughout this and I hovering here for an answer.. In my case the solution was to clear the browser history.

Isma'el
  • 23
  • 6
0

Not much has been said about those who use external js file: I had a similar issue. I had everything working well inside my blade file. But when I transferred all my js codes to external file, it stopped working.

First ensure that you have this in your app header

I have a default header for that at app.blade.php 

Secondly in your form you should have something like this

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

Thirdly in your external js file check this guys post https://stackoverflow.com/a/66120965/6511220 . Mine I placed the code at the top of my js file and used the "crsf" variable directly as token. i.e:

token=csrf;
$.ajax({
    url: 'yoururl', //change all these to suit your need.
     type: 'POST',
     data: 
    _token: token, 
     any_other_variables:here });   //etc..
Dlaw
  • 131
  • 2
  • 14
0

Sometimes it could be if you're using ULID or UUID field in users table. You may miss to change foreignUlid field in sessions table:

Schema::create('sessions', function (Blueprint $table) {
        $table->string('id')->primary();
        $table->foreignUlid('user_id')->nullable()->index();
        $table->string('ip_address', 45)->nullable();
        $table->text('user_agent')->nullable();
        $table->longText('payload');
        $table->integer('last_activity')->index();
    });

The reason is Laravel can't create session

Alexander
  • 59
  • 1
  • 2
  • 1
    I *really* wanted to get the database driver working instead of using file-based sessions, and this is ultimately what did it for me. If you're using a ULID or UUID for the users table, the default migration that sets up the sessions table won't work. Make sure the foreign key in the sessions table matches the format of the users table key. (Sounds obvious, but I spent way too much time debugging this.) – Justin Russell Aug 12 '23 at 05:51
0

for me, issue was with 'same_site' setting in config/session.php file

just disable/comment this line (or set it to null) :

#'same_site' => null

I have also set 'secure' and 'domain' to following values :

'secure' => false,
'domain' => env('SESSION_DOMAIN', '')

now my laravel project and login works within localhost, dev domain, and production domain. and login via mobile browsers works finaly (which returned 419 error on chrome and safari). also users can log in to our production domain via iframe (wordpress plugin usage)

hope this helps somebody

ob1y2k
  • 45
  • 5
-1

I also had a problem like this and I've discovered that the session files were locked for writing. So, I don't know if you are running your Laravel via stuff like vagrant or Docker, but I advise you to try to change the rights of the session directory (and files of course) (When you run Laravel in a VM you should change the rights locally and in the VM (like, when you share the files via NFS)

Like this:

chmod -R 777 storage/framework/sessions
chmod -R 777 storage/logs

I know, a 777 permission is the worst disaster that you can ever imagine. But they are handy for troubleshooting.

To be sure that I never forgot this I made a bash script. (Called it lalog, just because I wanted to clear the log files and set permissions)

Note: Make sure that you use this on the session directory. In config/session.php there is a files key declared with the location. In my case:

<?php
//...........
'files' => storage_path('framework/sessions'),
//...........

Location: /usr/bin/lalog (This is a file, not a directory)
Execute in shell as lalog

#!/bin/bash
rm -rf /home/username/Projects/x/storage/logs/laravel.log
echo "Laravel log removed"
touch /home/username/Projects/x/storage/logs/laravel.log
echo "Laravel log created"
chmod -R 777 /home/username/Projects/x/storage/
echo "CHMOD 777 on Storage dir"

Warning! This will allow write access for everyone, so be carefull with it! Also, maybe there is some usefull information in the log file of Laravel. (be sure to look in that log file before running my bash script)

Also, I know that it's already mentioned. But, be totally sure that you always

  1. Allow cookies in the browser, so the token can be set in the cookies
  2. Check if you are using the @csrf in your blade file

The form should be something like this

<form method="POST" action="{{ route('login') }}">
@csrf
.......
</form>
Koen Hollander
  • 1,687
  • 6
  • 27
  • 42
-1

You cannot do an empty return on Laravel 5.6 or greater. Laravel always expects a value to be returned. (I know from past experience). This is mainly to do with how PHP 7 handles empty returns.

Jamie Ross
  • 246
  • 1
  • 3
  • 13
-1

I have had similar problem and I found a solution to that

if you are echo or print something from controller while return to view this problem will pop up.

so make sure that you are not using echo or print when your controller returns

lionshell
  • 1
  • 1
  • 1
-1

Just to put it out there, i had the same problems. On my local homestead it would work as expected but after pushing it to the development server i got the session timeout message as well. Figuring its a environment issue i changed from apache to nginx and that miraculously made the problem go away.

Kees Hessels
  • 37
  • 2
  • 6
-1

I got this issue long time ago. I remembered it causes permission of storage/framework/sessions. You may want to change it by chmod -R 0777 storage/framework/sessions command. It worked for me.

Duy Nguyen
  • 334
  • 4
  • 10
-1

In my case, it is very ridiculous. I get error 419 when I put Auth::routes() at the top of the route file.

Auth::routes();

Route::middleware('auth')->group(function () {
    Route::get('/', 'DashboardController@index')->name('dashboard');
});

And I fixed the error by moving Auth::routes(); to bottom of the route file.

Route::middleware('auth')->group(function () {
    Route::get('/', 'DashboardController@index')->name('dashboard');
});

Auth::routes();

Maybe it can help your case as well. Good luck.

lyhong
  • 947
  • 1
  • 13
  • 23
-1

I just want to say, make sure the csrf token is generated, sometimes it's just an empty array, like for example in a repeater form if you don't generated inside the js query.

Ahmad Yousef
  • 621
  • 9
  • 20
-1

I had the very same problem in my development environment. It was resolved using http://127.0.0.1:8000 instead of http://localhost:8000.

Marc Brillault
  • 1,902
  • 4
  • 21
  • 41
-1

In my case deleting bootstrap/cache fixed the problem

Ahmad Mobaraki
  • 7,426
  • 5
  • 48
  • 69
-1

some line of code in app/Exceptions/Handler.php solved my problem.

public function render($request, Exception $exception)
{
    if ($exception instanceof Illuminate\Session\TokenMismatchException) {
        Artisan::call('cache:clear');
        Artisan::call('config:cache');
        return Redirect::back();
    }
    return parent::render($request, $exception);
}
Diyata
  • 43
  • 7
-1

If there is @csrf that you added then also the error occure please make sure that you have not blocked the cookies...

Click on Cookies and allow the link!

-1

This is a problem I have seen a few times and is usually when using apache.

If there are any stray characters or new lines before the opening <?php in any of the files that get executed then those characters are emitted by the web server before cookies are prepared and sent.

This blocks cookies from being send to the client, and the client has to start a new session on every request.

Unfortunately, the only solution is to look at every file you have created or modified (not too bad if you use Git) and ensure that <?php are the first characters in every php file.

You can ignore view files because they are not used until after the cookies are sent.

Most likely candidates are controllers, service providers and route files.

Tarik Manoar
  • 151
  • 3
  • 10
-1

For cloudways users,

Try to disable Varnish (caching layer) from Application Settings.

Jaydeep Mor
  • 1,690
  • 3
  • 21
  • 39
-1

I just changed my browser and it worked. If you have already added @csrf after your form and it's still not working just clear the cache of the browser use another browser it will work.

In my case, it worked hope this helps

Rahul Kumar Jha
  • 289
  • 1
  • 8
-1

For some, make sure also that your blade file is named with filename.blade.php not filename.php, this would result to 419 too.

DikoB
  • 27
  • 1
  • 5
-1

In my case I resolve mine when I had a debugging tool called barryvddh/laravel-debugbar by jnoordsij

Here is the link of the debugging tool which I recommend

Installation method

Require this package with composer. It is recommended to only require the package for development.

composer require barryvdh/laravel-debugbar --dev

Laravel uses Package Auto-Discovery, so doesn't require you to manually add the ServiceProvider.

The Debugbar will be enabled when APP_DEBUG is true.

If you use a catch-all/fallback route, make sure you load the Debugbar ServiceProvider before your own App ServiceProviders.

Laravel without auto-discovery: If you don't use auto-discovery, add the ServiceProvider to the providers array in config/app.php

Barryvdh\Debugbar\ServiceProvider::class,

If you want to use the facade to log messages, add this to your facades in app.php:

'Debugbar' => Barryvdh\Debugbar\Facades\Debugbar::class,

The profiler is enabled by default, if you have APP_DEBUG=true. You can override that in the config (debugbar.enabled) or by setting DEBUGBAR_ENABLED in your .env. See more options in config/debugbar.php You can also set in your config if you want to include/exclude the vendor files also (FontAwesome, Highlight.js and jQuery). If you already use them in your site, set it to false. You can also only display the js or css vendors, by setting it to 'js' or 'css'. (Highlight.js requires both css + js, so set to true for syntax highlighting)

Copy the package config to your local config with the publish command:

php artisan vendor:publish --provider="Barryvdh\Debugbar\ServiceProvider"

While using debug bar tool I've seen that Laravel initially selects * from sessions, having a column name id containing string so, I replaced the datatype from int to string

Then I looked for the migration file having sessions table file

I removed the duplicate migration file sessions table file

database/migrations/202_08_02_063945_create_sessions_table.php

I replaced the columns inside the sessions table

From

public function up()
{
    Schema::create('sessions', function (Blueprint $table) {
        $table->increments('id');
        $table->foreignId('user_id')->nullable()->index();
        $table->string('ip_address', 45)->nullable();
        $table->text('user_agent')->nullable();
        $table->longText('payload');
        $table->integer('last_activity')->index();
    });
}

To

public function up()
{
    Schema::create('sessions', function (Blueprint $table) {
        $table->string('id')->primary();
        $table->foreignId('user_id')->nullable()->index();
        $table->string('ip_address', 45)->nullable();
        $table->text('user_agent')->nullable();
        $table->longText('payload');
        $table->integer('last_activity')->index();
    });
}

Then migrate the sessions table only

In my case:

php artisan migrate:refresh --path=/database/migrations/202_08_02_063945_create_sessions_table.php

Then serve

php artisan serve

I hope this solves error 419 on registration and login issue including page session expired error

All the credits for solving belongs to jnoordsij for making the debugging tool

Two
  • 512
  • 4
  • 17
-1

1 - Go to Public folder open index.php after <?php ob_start()

This function will take the contents of the output buffer and returns a string that is to be sent to the browser for rendering and removes the spaces or line breaks you put before starting PHP.

2 - php artisan cache:clear

-4

Just change .env

SESSION_DRIVER=cookie
Udhav Sarvaiya
  • 9,380
  • 13
  • 53
  • 64
Danilo
  • 15
  • 4