cretueusebiu / laravel-vue-spa

A Laravel-Vue SPA starter kit.
https://laravel-vue-spa.cretueusebiu.com
MIT License
3.04k stars 964 forks source link

Middleware parameter #124

Closed TomasNiDo closed 3 years ago

TomasNiDo commented 6 years ago

How can I make vue-router middleware to accept a parameter? For example, just like how we add parameter to laravel middleware. e.g:

export default {
  middleware: 'role:client|admin',

  // ...
}
cretueusebiu commented 6 years ago

You'll have to modify the callMiddleware function to parse and pass the parameters to the middleware function.

imade-nl commented 5 years ago

Thanks for creating this repository. It's awesome! I needed the above middleware parameter. Here's my code if anyone needs it. router/index.js

function callMiddleware (middlewares, to, from, next) {
  const stack = middlewares.reverse()

  const _next = (...args) => {
    // Stop if "_next" was called with an argument or the stack is empty.
    if (args.length > 0 || stack.length === 0) {
      if (args.length > 0) {
        router.app.$loading.finish()
      }

      return next(...args)
    }

    const middleware = stack.pop().split(':')
    const middleware_name = middleware.shift()
    const middleware_params = middleware.length ? middleware.shift().split('|') : null

    if (typeof middleware_name === 'function') {
      middleware_name(to, from, _next, middleware_params)
    } else if (routeMiddleware[middleware_name]) {
      routeMiddleware[middleware_name](to, from, _next, middleware_params)
    } else {
      throw Error(`Undefined middleware [${middleware}]`)
    }
  }

  _next()
}

middleware/role.js (example)

import store from '~/store'

export default (to, from, next, roles) => {
  if(roles && Array.isArray(roles)){
    for (var i = 0; i < roles.length; i++){
      if ( ! store.getters['auth/hasRole'](roles[i])) {
        next('/404')
      }
    }
  }

  next()
}
cretueusebiu commented 5 years ago

Thanks! I'll make some changes and add it in the next release.

Tcheikovski commented 5 years ago

jimohalloran commented 4 years ago

I noticed this hadn't been incorporated into the project yet, so I raised the PR above to help ease the process.

cretueusebiu commented 3 years ago

Added https://github.com/cretueusebiu/laravel-vue-spa/commit/07baf5b09ceb1a851deb670e2b3c3551a96118c9