How do I resolve 419 page expired in Laravel PHP?

Published January 17, 2022

In Laravel applications, the 419 page expired error is very common. The error arises from an internal framework mechanism called CSFR (Cross-Site Request Forgery).

The layout of the error page varies between framework versions, but the error message is the same. Below is a screenshot of this error message in Laravel 8

 

How do I resolve 419 page expired in Laravel PHP?

 

To overcome this problem, every POST, PUT, PATCH, and DELETE request must include a csrf token as a parameter. You have numerous possibilities for appending this parameter depending on how you deliver your request. This post presents three ways that you can append your csrf token parameters to resolve this issue.

 

Solution 1: Implement the solution in Blade View.

The solution is relatively straightforward when you construct a form in a Blade template. The Blade template engine has a directive called @csrf that outputs a hidden HTML input holding the token. The directive should be put immediately after the opening form> tag.

 

<form method="POST" action="/register">

    @csrf

    <label for="email">Email</label>

    <input type="email" name="email">

    <label for="email">Password</label>

    <input type="password" name="password">

    <button type="submit">Save</button>

</form>

 

Alternately, you may use the csrf token() function to manually build a token input. The result will be the same.

<!-- Equivalent for @csrf directive -->

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

 

 

Solution 2: Modifying Header of the Ajax Request

The solution for an Ajax request is slightly different, but also pretty easy. All you should do is add the csrf token to the head section of your HTML page and submit it with your request as an X-CSRF-TOKEN header

<head>

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

</head>

 

 

Solution 3: You can disable the CSRF  endpoints validation

You can solve this problem by deactivating the CSRF validation for specified endpoints. In the $except an array of the VerifyCsrfToken class, certain URLs may be disallowed. This allows you to exclude either the precise URL or a collection of URLs that have a similar prefix

 

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

1448 Views