Cross-Site Request Forgery (CSRF) is a type of attack that performed by the attacker to send requests to a system with the help of an authorized user who is trusted by the system.
Laravel provides protection with the CSRF attacks by generating a CSRF token. This CSRF token is generated automatically for each user. This token is nothing but a random string that is managed by the Laravel application to verify the user requests.
How to Use: This CSRF token protection can be applied to any HTML form in Laravel application by specifying a hidden form field of CSRF token. The requests are validated automatically by the CSRF VerifyCsrfToken middleware.
There are three different ways in which you can do this.
Inspect Element Output:
Reference: https://laravel.com/docs/6.x/csrf
- @csrf
- csrf_field()
- csrf_token()
- Syntax:
<form method="POST"> @csrf // Generate hidden input field ..... ..... </form>
- Example:
html <!DOCTYPE html> <html> <head> <title>Laravel | CSRF Protection</title> </head> <body> <section> <h1>CSRF Protected HTML Form</h1> <form method="POST"> @csrf <input type="text" name="username" placeholder="Username"> <input type="password" name="password" placeholder="Password"> <input type="submit" name="submit" value="Submit"> </form> </section> </body> </html>
- Syntax:
<form method="POST"< // Generate hidden input field {{ csrf_field() }} ..... ..... </form> - Example:
html <!DOCTYPE html> <html> <head> <title>Laravel | CSRF Protection</title> </head> <body> <section> <h1>CSRF Protected HTML Form</h1> <form method="POST"> {{ csrf_field() }} <input type="text" name="username" placeholder="Username"> <input type="password" name="password" placeholder="Password"> <input type="submit" name="submit" value="Submit"> </form> </section> </body> </html>
- Syntax:
<form method="POST"> <input type="hidden" name="_token" value="{{ csrf_token() }}"> ..... ..... </form> - Example:
html <!DOCTYPE html> <html> <head> <title>Laravel | CSRF Protection</title> </head> <body> <section> <h1>CSRF Protected HTML Form</h1> <form method="POST"> <input type="hidden" name="_token" value="{{ csrf_token() }}"> <input type="text" name="username" placeholder="Username"> <input type="password" name="password" placeholder="Password"> <input type="submit" name="submit" value="Submit"> </form> </section> </body> </html>
Inspect Element Output:
Reference: https://laravel.com/docs/6.x/csrf