One in a lifetime, Laravel developers face CSRF token mismatch error message in the Laravel. CSRF token is very useful to protect the HTTP requests.
Throughout this article, we will learn about how to solve CSRF token mismatch error, change the error message in a user-readable form, how to exclude your special route from the CSRF protection, etc.
Let’s start this article with a bang!
Why CSRF Token Mismatch Error Occurs
As per our real-life experience we found that this error occurs due to the following reasons:
- You might forget to include a hidden CSRF (cross-site request forgery) token field in the form.
- If you are submitting an AJAX-based request using
jQuery
,JavaScript
,Vue
, etc then you might forget to include X-CSRF-TOKEN request header. - Your session might be expired and without refreshing a page, you are submitting a form or request.
These are the basic reasons for CSRF mismatch error occurs. Now, let’s see how to resolve the error.
Solution 01: Simple Form Submission
If you have the simple form and if you are not using any other mechanism to submit a form then you just need to include a hidden CSRF _token
field in the form so that the CSRF protection middleware can validate the request.
To do that you can use @csrf
blade directive that will generate hidden field automatically for you or you can write hidden field as below:
1
2
3
4
5
|
@csrf // Or <!-- Equivalent to... --> < input type = "hidden" name = "_token" value = "{{ csrf_token() }}" /> |
Both @csrf
and <input type="hidden" ...>
are equal as shown in the above code.
Solution 02: AJAX Based Requests
For the AJAX-based requests, you need to add the following meta
tag in <head></head>
1
|
< meta name = "csrf-token" content = "{{ csrf_token() }}" > // Add in < head ></ head > |
After that, include the following code before you request call
1
2
3
4
5
|
$.ajaxSetup({ headers: { 'X-CSRF-TOKEN' : $( 'meta[name="csrf-token"]' ).attr( 'content' ) } }); |
You don’t need to repeat the above code for each request. But you need to include the above code on each page where the request is being fired of.
Exclude URIs From CSRF Protection
Sometimes you may wish to exclude the URLs from the CSRF protection. For example, if you are using any 3rd party services and in that you might need to submit a form from your website in that case, you don’t need to use CSRF token.
If you don’t exclude that specific URL then Laravel show you the error message. So to exclude URI follow the steps as below:
- Go to the
app/Http/Middleware
directory and open theVerifyCsrfToken.php
file. - Now, in
protected $except
array, add your URIs like below and you are done.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<?php namespace App\Http\Middleware; use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware; class VerifyCsrfToken extends Middleware { /** * The URIs that should be excluded from CSRF verification. * * @var array */ protected $except = [ 'stripe/*' , 'http://example.com/foo/bar' , 'http://example.com/foo/*' , ]; } |
Change CSRF Token Mismatch Error Message In Laravel
Recently, we were working on a Laravel + Vue based project. In that, we have added auto logout functionality if a user is inactive for more than 15 mins. But after the logout session is expired and due to that if the user re-try to login they were getting the “CSRF token mismatch” error so they have reported this issue to the site admin.
So due to that site admin wants to change that message in user-readable form like “Your session has expired. You will need to refresh the page and log in again to continue using the system.” This message is meaningful to users and they won’t see the error message again after refreshing the page. Let’s see how to change the CSRF Token Mismatch error message.
- First, go to the
app/Exceptions
directory and open theHandler.php
file. - In
render()
method add the following code.
1
2
3
4
5
6
7
8
|
if ( $request ->expectsJson()) { if ( $exception instanceof TokenMismatchException) { return response()->json([ 'message' => 'Your session has expired. You will need to refresh the page and login again to continue using the system.' ], 419); } } |
That’s it. You are done.
If you want to test the newly added message then open your site and open the developer tools by inspect element option.
Then, Delete the XSRF-TOKEN
cookie and then try to submit your form or request again. You will see the newly added message.
Remove XSRF Token Using Browser’s Developer Tool
Additionally, read our guide:
- Laravel One To One Relationship Tutorial
- Best Way to Remove Public from URL in Laravel
- How To Print Or Debug Query In Laravel
- Specified Key Was Too Long Error In Laravel
- AJAX PHP Post Request With Example
- How To Use The Laravel Soft Delete
- How To Add Laravel Next Prev Pagination
- Laravel Remove Package With Example (Correct Way)
- Difference Between Factory And Seeders In Laravel
- Laravel: Increase Quantity If Product Already Exists In Cart
- How To Calculate Age From Birthdate
- How to Convert Base64 to Image in PHP
- Check If A String Contains A Specific Word In PHP
- How To Find Duplicate Records in Database
- How To Convert Word To PDF In Laravel
That’s it for now. We hope this article helped you to learn Laravel CSRF Token Mismatch Error Message related things.
Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you in advance. Keep Smiling! Happy Coding!