Search code examples
subdomainvuejs2laravel-5.4vue-router

Subdomains Laravel Routing and Vue.js


I'm using Laravel 5.4, vue.js 2.3 and vue-router.

Current situation

When example.com is hit, Laravel returns the app view which starts the Vue.app

web.php

Route::get('/', function () {
    return view('app');
});

app.js

const routes = [
    { path: '/', component: App },
];

const app = new Vue({
    el: '#app',
    router,
    data () {
        return {}
    },
});

App.vue

export default {
    ...
}

What I'm trying to do

If usa.example.com is typed, I would like the alert() in my App.vue to show usa.

If italy.example.com is typed, I would like the alert() in my App.vue to show italy.

I read the documentation of vue-router but I'm not sure wether it is a Laravel issue, a Vue issue or both.

App.vue

export default {
    ....
    created() {
        alert('subdomain is ' + $route.params.subdomain)
    }
}

Solution

  • VueRouter doesn't keep track of the subdomain.

    But, you can get the subdomain from the location and use that in your component's created method:

    created() {
      let subdomain = location.hostname.split('.').shift();
      alert('subdomain is ' + subdomain);
    }
    

    The above code is based off of this answer.