get user permissions with laravel vue rest api - laravel

I'm trying to get all user permissions with Laravel for backend and vuejs for frontend.
How can i get this from api to vue? what is the best choice?
I tried to get them with below code but shows me error
In the permissionMixin:
import PermissionDataService from '../../Servieces/PermissionDataService'
export default {
methods: {
checkPermission() {
let permissions;
PermissionDataService.get("user_permissions")
.then((response) => {
permissions= response.data;
})
.catch((error) => {
console.debug(error)
});
return hasAccess;
}
}
}
and that is how i used it in main.js:
import permission from "#/core/mixins/permissionMixin";
Vue.mixin(permission);
window.Laravel = this.checkPermission();
console.debug(Laravel)
Vue.directive('can', function (el, binding) {
return Laravel.permissions.indexOf(binding) !== -1;
});
but always shows me this error:
Uncaught TypeError: can't access property "defaults", a.default.axios is undefined
I am totally sure the endpoint is ok
ANY Idea?

Finally solved.
I had to put
window.Laravel = this.checkPermission();
into one of layout files

Related

Laravel Sanctum/Vuex Uncaught Error Vue Router Navigation Guard

Can anyone advise on this issue?
I've got a Laravel app with a Vue front-end, connecting to the API using Laravel Sanctum. (within the same application) I'm trying to set up the authentication guards so routes can only be accessed after authentication with the API.
I'm connecting through the state action like so:
async getAuthenticatedUser({ commit }, params) {
await axios.get('api/auth-user', { params })
.then(response => {
commit('SET_AUTHENTICATED', true)
commit('SET_AUTHENTICATED_USER', response.data)
localStorage.setItem('is-authenticated', 'true')
return Promise.resolve(response.data)
})
.catch(error => {
commit('SET_AUTHENTICATED', false)
commit('SET_AUTHENTICATED_USER', [])
localStorage.removeItem('is-authenticated')
return Promise.reject(error.response.data)
})
},
The state authenticated property is set as follows:
const state = () => ({
authenticated: localStorage.getItem('is-authenticated') || false,
authUser: [],
})
I have the following guard checking the auth. If I'm not signed in the app correctly redirects me back to the login screen when I access a route with the requiresAuth attribute.
However when I attempt to log in, I get Redirected when going from "/login" to "/dashboard" via a navigation guard.
router.beforeEach((to, from, next) => {
if (to.matched.some((record) => record.meta.requiresAuth)) {
if (store.getters["Auth/isAuthenticated"]) {
next()
return
}
next('/login')
}
if (to.matched.some((record) => record.meta.requiresVisitor)) {
if (! store.getters["Auth/isAuthenticated"]) {
next()
return
}
next('/dashboard')
}
next()
})
If it's safe to ignore, and you are using vue-router ^3.4.0, you can do:
import VueRouter from 'vue-router'
const { isNavigationFailure, NavigationFailureType } = VueRouter
...
this.$router.push(fullPath).catch(error => {
if (!isNavigationFailure(error, NavigationFailureType.redirected)) {
throw Error(error)
}
})

how set errors from laravel in vuejs

I am trying to retrieve errors from Laravel in Vue, but i get this error message in my console "Cannot set property 'errors' of undefined".
I have tried different approaches like direct assignment of errors and the $set() of vue to set error message to the error object of my data function, but it is still in vain.
This is my code
export default{
data(){
return{
form: {},
errors:{}
}
},
methods:{
async onSave() {
await Api().post('/stocks/store',this.form)
.then()
.catch(function (error) {
if(error.response && error.response.status == 422) {
let errors = error.response.data.errors;
// this.$set(this.$data.errors,'errors',errors)
console.log(errors);
this.errors = errors;
}
});
}
}
This is how the error message from my console
This is the error message from laravel
how do set this.errors with error message from laravel
If you look closely at the error, it says
Cannot set property 'errors' of undefined
So the problem is you are trying to set a property of an undefined object, in this case: this, your Vue component.
An easy and convenient way to solve this problem is to use arrow function instead of a regular function in your Promise.catch() callback. To put simply, a regular function expression has his own this context, where arrow function does not.
Here is a sample of code that should help you understand better:
new Promise().then()
.catch((error) => {
if(error.response && error.response.status == 422) {
this.errors = error.response.data.errors;
}
});
To learn more about arrow function and the binding of this

Laravel + Vue ssr. Prefetch data

I'm trying to make application lavevel + vue with server side render. I have found this manual and it works perfect. Bu there is a small problem. I need fetch data before page loading for SEO issues and I found official vue ssr manual for prefetch. But it does not work. I only see error in the console
entry-client.js:6952 [Vue warn]: Cannot find element: #app.
my entry-server.js
import {createApp} from './app'
export default context => {
return new Promise((resolve, reject) => {
const {app, router, store} = createApp();
router.push(context.url)
router.onReady(() => {
// This `rendered` hook is called when the app has finished rendering
context.rendered = () => {
context.state = store.state
}
resolve(app)
}, reject)
}).then(app => {
renderVueComponentToString(app, (err, res) => {
print(res);
});
})
.catch((err) => {
print(err);
})
}
Are there any idea how solve this problem?
Looks like Promise does not work
Laravel 5.7 and Vue 2.6.6

Vue js beforeRouteEnter

I am using laravel and vuejs for my app and every user has a role. Now I want to restrict users to access vue routes by their roles by redirecting them to another route if they can't access the page. I am using beforeRouteEnter for vuejs but I am getting an error
data() {
return{
role: '',
}
},
mounted() {
axios.post('/getRole')
.then((response) => this.role = response.data)
.catch((error) => this.errors = error.response.data.errors)
},
beforeRouteEnter (to, from, next) {
if (this.role === 'Admin') {
next()
}else {
next('/')
}
}
I am getting this error
app.js:72652 TypeError: Cannot read property 'role' of undefined
at beforeRouteEnter (app.js:90653)
at routeEnterGuard (app.js:72850)
at iterator (app.js:72690)
at step (app.js:72464)
at runQueue (app.js:72472)
at app.js:72726
at step (app.js:72461)
at app.js:72465
at app.js:72711
at app.js:72539
you can't use this in beforeRouteEnter function,because before the route updates, your component's vm does not exist.
in consideration of you put role information in your vm, you can use next to get your vm:
beforeRouteEnter(to, from, next) {
next(vm => {
// put your logic here
if (vm.role === 'Admin') {
}
})
}
actually,you should use the Global Router Guard ,and put your role information in global area,so that your can redirect your routing before your target component created

TypeError: Cannot read property 'props' of undefined in react-redux

I am using axios to create a restful api in my project.Based on the server response I am trying to dispatch an action.
restful api code
handleSubmit(e) {
console.log("form submit");
e.preventDefault();
const forms=new FormData(e.target);
axios.post("http://localhost:8080/reactLogin",forms).then(res=> {
console.log(res.data);
this.props.loginSubmit(res.data);
}).catch(err=>console.log(err))
}
code to dispatch action in react-redux
const mapStateProps=(state) => {
return {
userLogin:state.loginDetails
}
}
const mapDispatchProps=(dispatch) => {
return {
loginSubmit:(data) => {
console.log(data);
if(data.status==1) {
dispatch(loginSuccess(data.data[0]));
}
else {
dispatch(loginFail(data))
}
},
emailInputBorder:(data) => {
dispatch(emailBorder(data));
},
passwordInputBorder:(data) => {
dispatch(passwordBorder(data));
}
}
}
export default connect(mapStateProps,mapDispatchProps)(Login)
when i trying to dispatch an action in my restful api response it shows following error
TypeError: Cannot read property 'props' of undefined
what the issue here is?
If you are using a functional component, you can access the props directly without using the this keyword.
Access the method with something like props.loginSubmit directly.
Since I am not able to view your entire file, this is just a pre-assumption. It would be helpful if you could share the entire code.

Resources