Laravel Vue3 - Passing Token and User info to Vue store

Viewed 264

I'm creating a Laravel/Vue3 app and wanted to completely separate the Laravel router from the SPA router.

In order to achieve this I created a dashboard.blade.php file which contains the following content:

<x-app-layout>
  <div id="app"></div>
</x-app-layout>

Vue then simply mounts on top of that div and the app is started.

My webpack.mix.js:

const mix = require("laravel-mix");

mix.ts("resources/js/app.ts", "public/js")
    .vue({ version: 3 })
    .postCss("resources/css/app.css", "public/css", [
        require("postcss-import"),
        require("tailwindcss"),
        require("autoprefixer"),
    ]);

The app.ts file is also quite simple:

import { createApp } from 'vue';
import App from './App';
createApp(App).mount('#app');

Which is great, but my holdup is that for subsequent requests (via Axios), I will need the user token. How can I get this token/logged in user info to my Vue3 app?

I'm using Laravel Breeze for authentication (if that helps).

Thank you,

1 Answers

It turns out the answer was 'extremely' simple. I had to do nothing besides removing the comment tags on this line:

enter image description here

And add headers as follows in your axios config:

import axios from "axios";
import store from "../store";

const Axios = axios.create({
    baseURL: process.env.APP_URL,
    headers: { Accept: "application/json" },
});

Axios.interceptors.request.use(
    (config) => {
        store.commit("setLoader", true);
        return config;
    },
    (error) => Promise.reject(error)
);

Axios.interceptors.response.use(
    (response) => {
        store.commit("setLoader", false);
        return response;
    },
    (error) => Promise.reject(error)
);
export default Axios;

Subsequent axios calls have the token attached automatically.

You can find all the required information here. Love Laravel...

Related