Laravel 5: Generating CSRF Hidden HTML Fields With csrf_field

April 14, 2018 —John Koster

The csrf_field function can be used to generate a hidden HTML element containing the value of the CSRF token. These tokens can help to prevent cross-site request forgeries.

#Signature

The signature of the csrf_field function is:

1function csrf_field();

#Example Use

For example, the following HTML code can be greatly simplified using the function:

1<!DOCTYPE html>
2<html>
3<head>
4 <title>CSRF Token Form Sample</title>
5</head>
6<body>
7 <form>
8 <input type="hidden" name="_token"
9 value="<?php echo csrf_token(); ?>">
10 
11 <!-- Other form inputs here -->
12 </form>
13</body>
14</html>

can be simplified to just:

1<!DOCTYPE html>
2<html>
3<head>
4 <title>CSRF Token Form Sample</title>
5</head>
6<body>
7 <form>
8 <?php echo csrf_field(); ?>
9 
10 <!-- Other form inputs here -->
11 </form>
12</body>
13</html>

or with Blade syntax:

1<!DOCTYPE html>
2<html>
3<head>
4 <title>CSRF Token Form Sample</title>
5</head>
6<body>
7 <form>
8 {!! csrf_field() !!}
9 
10 <!-- Other form inputs here -->
11 </form>
12</body>
13</html>

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.