Search code examples
laravelyajra-datatable

Laravel Yajra datatables action button with csrf still throws 419


I am using Yajra Datatables for Laravel to show a file list with post button actions.

I have this download button with the post method in order to check authorization whether the user is allowed to download that current file or not.

I have inspected the page and I do see the CSRF token. However, Laravel still throws 419 error.

Here is a piece of the controller code where I am generating a post button inside a Form with its CSRF token:

return DataTables::of($mediaItems)
     //...
     //ACTION BUTTONS
     ->addColumn('action',function (Media $file){
          $button = '<form method="post" action="'.route('download.file',['media'=>$file]).'">
                        <meta name="csrf-token" content="'.csrf_token().'">
                        <button type="submit" name="download" class="btn btn-info" title="Download file"><i class="fas fa-file-download"></i></button>
                     </form> ';
          return $button;
})
->toJson();

And right at the web browser's inspect element on the view, this is what I see:

<form method="post" action="http://myApp.local/file/download/z271dd4u-b0a2-44f6-a0a5-cmxd33de3e15">
      <meta name="csrf-token" content="O02W6Fu9BoW1futzAL06BbFmDfsS8lgmmx4Vd05A">
      <button type="submit" name="download" class="btn btn-info" title="Download"><i class="fas fa-file-download"></i></button>
</form>
                            
                            

When I click on the download button, why do I still get the 419 page expired error?


Solution

  • you have to pass csrf token as value. when you use @csrf in a form and inspect the form, you will find out that, it generates a hidden input field with name _token and the value is csrf token. you can't pass value with request using meta tag. so instead use the hidden input field.

    <input type="hidden" name="_token" value=" '.csrf_token().' ">