1

I am using Laravel and VueJs for my app, and I want to integrate a section for roles and permissions and for that I am using Spatie.

In app, each user can have multiple Roles (like: admin, teacher, editor) and each role has some permissions.

I tried some stuff from here , Shuyi's answer but I get some errors.

The questions is how can I check roles in VueJS?

Controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class TeachersController extends Controller
{
    function check($permissionName) {
        if (! Auth::user()->hasPermissionTo($permissionName)) {
             abort(403);
        }
        return response('', 204);
     }
}

web.php

Route::group(['middleware' => 'auth'], function () {
   Route::get('/permission/{permissionName}', 'PermissionController@check');
});

app.js

Vue.mixin("can", (permissionName) => {
    let hasAccess;
    axios.get(`/permission/${permissionName}`)
        .then(() => {
            hasAccess = true;
        })
        .catch(() => {
            hasAccess = false;
        });
    return hasAccess;
});

App.vue

<template>
    <button v-if="can('write-stuff')">Just a test!</button>
</template>

Property or method "can" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

tony19
  • 125,647
  • 18
  • 229
  • 307
Beusebiu
  • 1,433
  • 4
  • 23
  • 68

1 Answers1

1

If you are not defining you mixin as global, you have to inject it in the component you want to use, as explained in the Vue Mixins docs

Per component registration:

// define a mixin object
var myMixin = {
  created: function () {
    this.hello()
  },
  methods: {
    hello: function () {
      console.log('hello from mixin!')
    }
  }
}

// define a component that uses this mixin
var Component = Vue.extend({
  mixins: [myMixin]
})

Global registration (will be available in all components )

// inject a handler for `myOption` custom option
Vue.mixin({
  created: function () {
    var myOption = this.$options.myOption
    if (myOption) {
      console.log(myOption)
    }
  }
})

new Vue({
  myOption: 'hello!'
})
tony19
  • 125,647
  • 18
  • 229
  • 307
Raffobaffo
  • 2,806
  • 9
  • 22