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

upnorthal's avatar

Passing Data to Alpine.JS

What is the best way to get data from my database, to Alpine.JS

Say I have the following in my controller

   $component =  DB::table('config_pathway')
            ->select( 'height','width','x','y')
            ->get();

  return view('chart', compact('component'));

In my blade template I don't seem to be able to echo the view variable directly into the x-data object

<div  x-data="$component"> </div>

I have tried several variation of the above. Each attempt results in the error

Uncaught ReferenceError: $component is not defined

Yet I can access $component elsewhere in my template

Thanks

0 likes
7 replies
Sinnbeck's avatar

Try this

<div  x-data="@json($component)"> </div>
upnorthal's avatar

thanks. I gave that a go but got

alpine.js:115 Uncaught SyntaxError: Unexpected token ';'

I wonder if something in the data has upset it...

Sinnbeck's avatar

Then this?

<div  x-data="{{json_decode($component)}}"> </div>
upnorthal's avatar

Managed to sort this in the end, the following works .

<div
    x-data="{
    bodys: {{  $component }} }
 ">

Thanks for your help. I will change the variable name from component as that is just plain confusing given the Javascript frameworks pinched that name first ! :)

cwhite's avatar

You can also use Js::from() without having to import

1 like

Please or to participate in this conversation.