2
votes

I am working on a Vue application that's living in a Laravel project. I bind my vue instance to an id that's placed in a blade file.

What I would like to do is to pass the logged user to my Vue instance from Laravel/blade. Is there a way to do this? I know you can pass data through props but this here is just a regular div with an id of #root that's binding the Vue instance. I know how to get the logged user, but I am specific looking for an way to directly pass the data from blade to my vue instance.

app.js

// Require the deps from laravel (jQuery, axios, Bootstrap)
require('./bootstrap');

// Import vue deps
import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter)

// Import the router & routes
import router from './routes'

// Init a new vue instance
const root = new Vue({
    el: '#root',
    data: {
        User: name here..
    },
    router
});

Blade

@extends('layouts.app')

@section('content')

<!-- pass user below -->
<div id="root"></div>

@endsection
3

3 Answers

3
votes

In your blade file, pass the logged user information to a javascript global variable. Let's say you just want the user id and name:

<script>
    window.auth_user = {!! json_encode([
        'id'     => auth()->user()->id,
        'name'   => auth()->user()->name
    ]) !!};
</script>

Then in your javascript, you can access the auth_user global variable. For example, to log the user name:

console.log(auth_user.name)

or

console.log(window.auth_user.name)
0
votes

You have few options (I think I not list all) e.g:

  1. You can pass data by converting them to json and write as HTML element or attribute and then read it from vue using e.g. document.querySelector(...) - more info here: Best way to store JSON in an HTML attribute?

  2. You can change a littlebit architecture and create separate (Restful) API which your vue components will be use via ajax to read data (e.g. you can create GET api/v1/currentUser do read current logged user)

  3. Completly change your architecture - to "microservices" - so in laravel only create Restful API, and creatte SEPEARATE project with vue (and NO laravel) user interface which use that API (it is modern approach to separation backend from frontend). You will face CORS problem in this approach but its no so hard (only at first time).

0
votes

You might want to take a look at the PHP-Vars-To-Js-Transformer package. You can use it either in your controller or in a @php directive.
Probably not a good practice with VueJS though.