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

vincenl83's avatar

Pass a variable to VUEJS

Hello,

Is it possible to call a variable I passed through a view with VUE JS?

For example I'm passing through the variable 'overview', how can I access the values in that variable through Vuejs?

public function overview()
{
    $overview = Improve::all();
    return view('store.improve.overview', compact('overview'));
}
0 likes
8 replies
RachidLaasri's avatar

You can access that variable if you are using inline JavaScript, but if you use an external file you can't do that unless you grab it from the DOM.

opheliadesign's avatar

@RachidLaasri what I usually do is grab it before initializing Vue.. for example (using jQuery here)

var foo = $("#bar").val(); // or whatever..

var vm = new Vue({
    el: '#demo',
    data: {
    foobar: foo
   }
});
2 likes
TheBlueDragon's avatar

guys did anyone try to use this package ?

https://github.com/laracasts/PHP-Vars-To-Js-Transformer

i think the idea can be implemented with this package easily as we will not need an api or different routes to grab some data we can do most of it in the controller method with returning the view we want

now iam grabbing this package and try it ^^

3 likes
guillaume.caggia's avatar

Following your code, the easiest solution is to pass directly to your data variable of your view model binding like this :

var vm = new Vue({
    el: '#demo',
    data: {
        overview: {!! json_encode($overview->toArray()) !!},
   }
});
Abi's avatar

There are multiple ways to do so.

1- You can use inline templates that would allow you to use php.

2- you can send them through properties

3- grabbing them from the DOM with jQuery.

4- Use the nice wrapper that Blue dragon mention

5- Create a provider that returns javascript to the views something like

   public function boot()
    {
        \View::composer('*', function($view){
          

            echo "<script>window.hello = 'a';</script>";
          
        });
    }

Hawkeye64's avatar

I just did this and it's working great for me. Using Laravel 5.4 and Vue 2.x.

In my component, declare a property (props) for the object:

props: ['currentUser'],

On my blade page where the component is instantiated:

<my-component v-bind:current-user='{!! Auth::user()->toJson() !!}'></my-component>

Note that in the component, I am using camelCase for currentUser, but because html is case-insensitive, you have to use kebab-case (thus, the 'current-user').

3 likes

Please or to participate in this conversation.