search
HomeBackend DevelopmentPHP TutorialHow to pass CSRF token via Ajax request in Laravel?

CSRF stands for Cross-Site Request Forgery. CSRF is malicious activity performed by an unauthorized user pretending to be authorized.

Laravel protects against such malicious activity by generating a csrf token for each active user session. The token is stored in the user's session. It is always regenerated if the session changes, so the token is verified every session to ensure an authorized user is performing any task. The following is an example of accessing csrf_token.

Generate csrf token

You can obtain the token in two ways.

  • By using $requestsession()token()

  • Use the csrf_token() method directly

Example

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Student;

class StudentController extends Controller {
   public function index(Request $request) {
      echo $token = $request->session()->token();
      echo "<br/>";
      echo $token = csrf_token();
   }
}

Output

The above output is -

13K625e8mnDna1oxm9rqjfAPfugtTlYdndBoNR4d
13K625e8mnDna1oxm9rqjfAPfugtTlYdndBoNR4d

CSRF token in blade template

Whenever you have to use POST, PUT, PATCH, DELETE in html form, make sure to use csrf token as hidden field in html form. This will ensure that requests made are protected by CSRF middleware protection.

In blade template you can use @csrf directive to help you generate csrf token which can later be stored as a hidden field as shown below -

Example

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Student;

class StudentController extends Controller {
   public function index(Request $request) {
      return view('hello');
   }
}

hello.blade.php

<form method="POST" action="/student">
   @csrf
   
   <!-- Equivalent to... -->
   <input type="hidden" name="_token" value="{{ csrf_token() }}" />
</form>

How to pass CSRF token via Ajax request in Laravel?

Using csrf tokens in Ajax requests

Ajax request will be used here and the csrf token will be passed in it. Using csrf tokens with Ajax. You need to add csrf token in head section of html like below -

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

Include the jquery file in the html because we will use $.ajaxSetup() and $.ajax to make the ajax calls.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

Later call ajaxsetup using the header as shown below -

$.ajaxSetup({
   headers: {
      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
   }
});

Now make the ajax call as shown below -

$.ajax({
   type:'POST',
   url:'/getdata',
   success:function(data) {
      $("#data").html(data.msg);
   },
   
   error: function (msg) {
      console.log(msg);
   var errors = msg.responseJSON;
   }
});

The complete code in ajaxtest.blade.php is -



   Ajax CSRF TOKEN Example
   <meta name="csrf-token" content="{{ csrf_token() }}">
   
   
   <script>
      function getData() {
         console.log("ABCD");
         $.ajaxSetup({
            headers: {
               'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
         });
         $.ajax({
            type:'POST',
            url:'/getdata',
            success:function(data) {
               $("#data").html(data.msg);
            },
            error: function (msg) {
               console.log(msg);
               var errors = msg.responseJSON;
            }
         });
      }
   </script>


   
'/ajaxtest'));?> 'getData()']);?>

AjaxCSRFController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;

class AjaxCSRFController extends Controller {
   public function index() {
      $data = "Hello World";
      return response()->json(array('msg'=> $data), 200);
   }
}

Create a route for CSRF testing in routes/web.php

Route::get('ajaxtest',function() {
   return view('ajaxtest');
});
Route::post('/getdata',[AjaxCSRFController::class, 'index']);

Now click on the URL in your browser: http://localhost:8000/ajaxtest and you will get the following output-

How to pass CSRF token via Ajax request in Laravel?

The above is the detailed content of How to pass CSRF token via Ajax request in Laravel?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
Dependency Injection in PHP: Avoiding Common PitfallsDependency Injection in PHP: Avoiding Common PitfallsMay 16, 2025 am 12:17 AM

DependencyInjection(DI)inPHPenhancescodeflexibilityandtestabilitybydecouplingdependencycreationfromusage.ToimplementDIeffectively:1)UseDIcontainersjudiciouslytoavoidover-engineering.2)Avoidconstructoroverloadbylimitingdependenciestothreeorfour.3)Adhe

How to Speed Up Your PHP Website: Performance TuningHow to Speed Up Your PHP Website: Performance TuningMay 16, 2025 am 12:12 AM

ToimproveyourPHPwebsite'sperformance,usethesestrategies:1)ImplementopcodecachingwithOPcachetospeedupscriptinterpretation.2)Optimizedatabasequeriesbyselectingonlynecessaryfields.3)UsecachingsystemslikeRedisorMemcachedtoreducedatabaseload.4)Applyasynch

Sending Mass Emails with PHP: Is it Possible?Sending Mass Emails with PHP: Is it Possible?May 16, 2025 am 12:10 AM

Yes,itispossibletosendmassemailswithPHP.1)UselibrarieslikePHPMailerorSwiftMailerforefficientemailsending.2)Implementdelaysbetweenemailstoavoidspamflags.3)Personalizeemailsusingdynamiccontenttoimproveengagement.4)UsequeuesystemslikeRabbitMQorRedisforb

What is the purpose of Dependency Injection in PHP?What is the purpose of Dependency Injection in PHP?May 16, 2025 am 12:10 AM

DependencyInjection(DI)inPHPisadesignpatternthatachievesInversionofControl(IoC)byallowingdependenciestobeinjectedintoclasses,enhancingmodularity,testability,andflexibility.DIdecouplesclassesfromspecificimplementations,makingcodemoremanageableandadapt

How to send an email using PHP?How to send an email using PHP?May 16, 2025 am 12:03 AM

The best ways to send emails using PHP include: 1. Use PHP's mail() function to basic sending; 2. Use PHPMailer library to send more complex HTML mail; 3. Use transactional mail services such as SendGrid to improve reliability and analysis capabilities. With these methods, you can ensure that emails not only reach the inbox, but also attract recipients.

How to calculate the total number of elements in a PHP multidimensional array?How to calculate the total number of elements in a PHP multidimensional array?May 15, 2025 pm 09:00 PM

Calculating the total number of elements in a PHP multidimensional array can be done using recursive or iterative methods. 1. The recursive method counts by traversing the array and recursively processing nested arrays. 2. The iterative method uses the stack to simulate recursion to avoid depth problems. 3. The array_walk_recursive function can also be implemented, but it requires manual counting.

What are the characteristics of do-while loops in PHP?What are the characteristics of do-while loops in PHP?May 15, 2025 pm 08:57 PM

In PHP, the characteristic of a do-while loop is to ensure that the loop body is executed at least once, and then decide whether to continue the loop based on the conditions. 1) It executes the loop body before conditional checking, suitable for scenarios where operations need to be performed at least once, such as user input verification and menu systems. 2) However, the syntax of the do-while loop can cause confusion among newbies and may add unnecessary performance overhead.

How to hash strings in PHP?How to hash strings in PHP?May 15, 2025 pm 08:54 PM

Efficient hashing strings in PHP can use the following methods: 1. Use the md5 function for fast hashing, but is not suitable for password storage. 2. Use the sha256 function to improve security. 3. Use the password_hash function to process passwords to provide the highest security and convenience.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool