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.
<form method="POST"> @csrf // Generate hidden input field ..... ..... </form>
<!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>
csrf_field(): This function can be used to generate the hidden input field in the HTML form.
Note: This function should be written inside double curly braces.
Syntax
<form method="POST"<
// Generate hidden input field
{{ csrf_field() }}
.....
.....
</form>
<!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>
csrf_token(): This function just gives a random string. This function does not generate the hidden input field.
Note: HTML input field should be written explicitly. This function should be written inside double curly braces.
<form method="POST">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
.....
.....
</form>
<!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>