Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

deansatch's avatar

Laravel charts ajax and csrf

I have an api to be consumed by the same site. I am using laravel charts and want to use the api endpoints to build the datasets and use ajax to load them.

Following the laravel charts docs (https://charts.erik.cat/api_charts.html#building-the-chart) I have used their example data for now as my endpoint (api/v1/test) and set up the view exactly as their example. It fails authorisation on page load so the chart never loads.

I am guessing this is because it uses fetch() but isn't setting a csrf header but I have no idea how to inject that header in this case.

A quick test with jquery $.get() setting the jquery csrf header I am authenticated and can return the data.

0 likes
4 replies
deansatch's avatar

Just like the example really...but to clarify a bit better, here is my api controller (index method):


    $chart = new Test();
        $chart->dataset('Sample Test', 'bar', [3, 4, 1]);
        $chart->dataset('Sample Test', 'line', [1, 4, 3]);
        return $chart->api();

And my api route:


Route::group(['namespace' => 'API', 'prefix' => 'v1'], function () {
    Route::group(['middleware' => ['auth:api']], function () {
        Route::get('test', 'ChartController@index');
    });
});

And my view:

@extends('layouts.main')
@section('content')
        {!! $chart->container() !!}
@endsection

@section('footerscripts')
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js" charset="utf-8"></script>
{!! $chart->script() !!}

<script>
    {{ $chart->id }}_refresh({{ $chart->id }}_api_url);
</script>

@endsection

Controller method for the view:


$url = url('/api/v1/test');
        $chart = new Test();
        $chart->labels(['test1', 'test2', 'test3'])->load($url);
        return view('charts.test', compact('chart'));


deansatch's avatar

Can anyone else help on this? If I remove 'auth:api' from the api route it works ok.

palla451's avatar

@deansatch i

I solved it changing return $chart->api(); with return json_decode($chart->api());

1 like

Please or to participate in this conversation.