- Get link
- X
- Other Apps
- Get link
- X
- Other Apps
I spent plenty of time looking for this on my own and most solutions are not very helpful so I have found my own way to do this. Most people can setup a Laravel login environment so this is targeted at those who are either converting or using a small amount of Laravel in their project to run the authentication system instead of a javascript based solution (VueJS).
One of the things I noted in my early usage of VueJS is that you can pass data to components and that VueJS is essentially a component. Some more experienced users might be able to guess where I am going from this. Anyway, here is an example:
<Breadcrumbs parents="['parent1', 'parent2']"></Breadcrumbs>
In the example above I am manually inputting an array and passing the array through to the Breadcrumbs component as the property parents.
This is defined on the Breadcrumbs component like so:
<script>
export default {
name: "BreadCrumbs",
props:['parents'],
}
</script>
So I thought about it and realised I might be able to use this method to pass the authentication token to the VueJS application.... and I was right.
So here is the Laravel blade Vue app declaration:
<v-app token="{!! auth()->user()->getRememberToken() !!}">
<router-view></router-view>
</v-app>
As can be seen here, I have added a token (without the : at the start) to pass to the v-app which gets the Remember Token in this case but you can use whatever you want to use as an authentication token. This should be something unique to the logged in user however.
Next we need to handle this now in VueJS. This is pretty easy, as mentioned before, setting up as a property will suffice so here is my app declaration.
const app = new Vue({
props:['token'],
router,
moment,
el: '#app',
vuetify
});
This has now injected the authentication property into the application itself. This can usually be found in resources/js/app.js in Laravel.
The last thing is how to use this token now. Here is the token call in VueJS:
this.$parent.$attrs.token
This can be accessed on all component pages in this way meaning you dont have to save it anywhere else! By all means shred my security on this method but it works. I use this token method to make API calls to Laravel using the auth:api guarded routes.
Comments