Now that we have authorization for the back-end, let's add it for the front-end, too. If the user cannot delete the post, then he shouldn't even see the delete button.
For front-end permissions, we will use the package CASL Vue. First, let's install it.
npm install @casl/vue @casl/ability
To get started, we need to import abilitiesPlugin
and ability
from the services in the main app.js
.
resources/js/app.js:
import './bootstrap'; import { createApp, onMounted } from 'vue' import router from './routes/index'import VueSweetalert2 from 'vue-sweetalert2';import useAuth from './composables/auth';import { abilitiesPlugin } from '@casl/vue'; import ability from './services/ability'; createApp({ setup() { const { getUser } = useAuth() onMounted(getUser) }}) .use(router) .use(VueSweetalert2) .use(abilitiesPlugin, ability) .mount('#app')
And what is inside this /services/ability
? You define the abilities there, and one of the sections in the documentation is about ability builder. And we can copy the code in that services file.
resources/js/services/ability.js:
import { AbilityBuilder, Ability } from '@casl/ability' const { can, cannot, build } = new AbilityBuilder(Ability); export default build();
But instead of defining can and cannot here, we will define them based on...