Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass Laravel data into Vue root instance with Laravel Mix Setup

So I am using Laravel 5.5. I have a data coming from my Controller and I want to pass it to my root vue instance not the component.

So for example I have the Dashboard Controller which has a data of "users"

class DashboardController extends Controller {

    public function index(){

       $user = User::find(1);

       return view('index', compact('user'));

    }

}

I am using Larave mix on my project setup. So my main js file is the app.js. That "$user" data I need to pass on the root Vue instance. Which is located in app.js

const app = new Vue({
    el: '#dashboard',

    data: { 
        // I want all the data from my controller in here.
    },

});
like image 479
Yves Gonzaga Avatar asked Dec 30 '25 19:12

Yves Gonzaga


1 Answers

If you don't want to use an API call to get data (using axios or else), you could simply try this :

JavaScript::put(['user' => $user ]);

This will, by default, bind your JavaScript variables to a "footer" view. You should load your app.js after this footer view (or modify param bind_js_vars_to_this_view).

In app.js :

data: { 
    user: user
}

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

like image 116
soju Avatar answered Jan 02 '26 10:01

soju