How to get CSRF token in laravel controller

Updated at 19-Aug-2021, By samar

How to get CSRF token in laravel controller

We will use programming in this lesson to attempt to solve the "How to get CSRF token in laravel controller".

You can get CSRF token in laravel controller using csrf_token() method in your controller method. You can use csrf token in the controller to pass csrf token to html form and return to view file on call ajax() using jQuery.
  • Get CSRF token in laravel controller

    //routes\web.php
    use App\Http\Controllers\HomeController;
    Route::get('/get-csrf-token', [HomeController::class, 'getCSRFToken']);
    
    //app\Http\Controllers\HomeController.php
    //Controller’s method inside HomeController class
    public function getCSRFToken(){
        return csrf_token();
    }
    
    //view blade file
    <a href="http://localhost:8000/get-csrf-token" target="_blank" rel="noopener">http://localhost:8000/get-csrf-token</a>
    
    //Output :
    Oo8RYv6TRVHIydg9ps9ojKWYOPRsx8C8TeQA5PPm
    

Back to code snippet queries related laravel