How To Use CSRF Token in Laravel

How To Use CSRF Token in Laravel

In this tutorial, we are learning how to use CSRF token in Laravel. you make Forms of any type Laravel uses CSRF tokens to add another layer of security on top of your web application this is very important.

Laravel CSRF token in form requires HTML forms and submitting data from the front-end to the back-end controllers. If there is no CSRF token in any form, then it will not allow submitting this form and redirect repeatedly and give an error. Many times laravel CSRF token not working visit this site.

In this tutorial guide, we will learn how to use CSRF tokens in two ways that CSRF protects your any form no spam is allowed.

Method 1 – Adding the CSRF Token in Laravel Meta Tag

In this step Add the CSRF token into the head section of your HTML.

Generally, this method will be coded into the Layouts/Header file or similar. laravel form token.

Add the following code to your file

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

Then, will yield something like the following when the page is rendered CSRF token Laravel.

<meta name="csrf-token" content="tn18h6ggZmd06aL8Mo3ge6bQPQOAP0vPYZlyBnkef">

Method 2 – Adding the CSRF Token Input Field

In this step, if you Submitting the form, then Laravel expects to see a CSRF token field within the JSON type that is submitted to the controller. This token will be validated specifically your application to enhance the security cress-site requests and any request.

See this form

<form method="post" action="{{ route('mycontroller.create') }}" >
         
    <label for="Name">Full Name</label>
    <input type="text" class="form-control" name="full-name"/>
                
    <button type="submit" class="btn btn-primary">Submit</button>
</form>

If this form was submitted, Laravel would stop the request as there is no CSRF token present in this form.

So, we need to do is add the following Laravel blade syntax.

@csrf

So, This form will look like this after adding the CSRF token

<form method="post" action="{{ route('mycontroller.create') }}" >
     @csrf
    <label for="Name">Full Name</label>
    <input type="text" class="form-control" name="full-name"/>
                
    <button type="submit" class="btn btn-primary">Submit</button>
</form>

This form would yield something like the following:

<form method="post" action="http://localhost/mycontroller/create" >
    <input type="hidden" name="_token" value="tn18h6ggZmd06aL8Mo3ge6bQPQOAP0vPYZlyBnkef">
    <label for="Name">Full Name</label>
    <input type="text" class="form-control" name="full-name"/>      
    <button type="submit" class="btn btn-primary">Submit</button>
</form>

When we submit the form, it will get the CSRF token and when it receives the CSRF token, it will be successfully submitted and stored in the database.

Leave a Reply

Your email address will not be published. Required fields are marked *