Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 419 Page Expired, works on local

I recently added a new feature to my website so that admins are able to view and delete files in storage/app/public/files/uploads

This feature works fine in my local copy but on the live server I keep getting a 419 page expired. I searched around the web and found that the most likely cause is a missing @csrf at the start of my form but I already have this in my code.

<form method="POST" action="{{route('dashboard.uploaddelete', $file)}}">
    @csrf
    <div class="modal-body">
        <p class="font-weight-bold">Are you sure you wish to delete {{$file}}? This action is irreversible!</p>
        <input type="hidden" name="filename" value="{{$file}}">
    </div>
    <div class="modal-footer">
        <button type="submit" class="btn btn-danger">Delete</button>
        <button type="button" class="btn btn-light" data-dismiss="modal">Cancel</button>
    </div>
</form>

I have tried clearing artisan cache, routes, views and config but no luck.

Any help would be appreciated, thanks!


1 Answers

Mostly 419 error is thrown when the csrf token is being mismatched.

  • Firstly, try using the webstie in the incognito window, if it worked then the issue is with the cache memories.

  • You can manually view the csrf token: {{ csrf_token() }} and check whether it matches with the token saved in the session.

  • You can increase the life time of the session in config/session.php file by changing the lifetime value or change it in the .env file by using this SESSION_LIFETIME=120

  • Check both the form and your site uses HTTPS protocol

  • Check .env config, make sure you have both SESSION_DOMAIN and APP_URL are same

If you are using AJAX call, then you need to pass the csrf token in the header.

  • Add an meta tag to save the csrf token in it

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

  • Then in your ajax, add the header

headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}

You can try this method but it is not recommended:

If you want to turn off the CSRF protection for a specific route in Laravel, you need to add the below lines in the app/Http/Middleware/VerifyCrsfToken.php file

//add an array of Routes to skip CSRF check
private $exceptUrls = ['controller/route1', 'controller/route2'];
//modify this function
public function handle($request, Closure $next) {
//add this condition foreach($this->exceptUrls as $route) {
if ($request->is($route)) {
  return $next($request);
}
}
return parent::handle($request, $next);
}

refer https://hackr.io/blog/top-laravel-interview-questions-and-answers 32nd question.

like image 60
Harshavardhan Avatar answered Oct 28 '25 13:10

Harshavardhan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!