Setting up Vue.js with Laravel Sanctum Authentication using the Vue Composition API

Posted by

Installing Vue.js with Laravel Sanctum Authentication and Vue Composition API

Installing Vue.js with Laravel Sanctum Authentication and Vue Composition API

If you are building a web application with Laravel as the backend and Vue.js as the frontend framework, you may want to implement user authentication using Laravel Sanctum and the Vue Composition API. Here’s how you can install Vue.js and set up authentication using these technologies.

Step 1: Install Vue.js

First, you need to install Vue.js in your Laravel project. You can do this by running the following command in your terminal:

npm install vue

This will install Vue.js as a dependency in your project.

Step 2: Install Laravel Sanctum

Next, you need to install Laravel Sanctum in your Laravel project to handle user authentication. You can do this by running the following command in your terminal:

composer require laravel/sanctum

This will install the Sanctum package and its dependencies in your Laravel project.

Step 3: Set up Vue Composition API

Now that you have Vue.js and Laravel Sanctum installed, you can set up the Vue Composition API for handling authentication in your Vue.js components. You can do this by creating a new CompositionAPI.js file in your Vue.js project and importing it in your components.

    // CompositionAPI.js
    import { ref } from 'vue';
    import axios from 'axios';

    const user = ref(null);

    const fetchUser = async () => {
        const response = await axios.get('/api/user');
        user.value = response.data;
    };

    export { user, fetchUser };
    

In this example, we are using the ref function to create a reactive user variable and the axios library to make HTTP requests to the backend API. We also have a fetchUser function that fetches the authenticated user’s data from the backend.

Step 4: Use Vue Composition API in Components

Finally, you can use the Vue Composition API in your Vue.js components to handle authentication. You can import the user and fetchUser functions from the CompositionAPI.js file and use them in your components to fetch and display the authenticated user’s data.

    // UserComponent.vue
    
        

Authenticated User

Name: {{ user.name }}

Email: {{ user.email }}

import { user, fetchUser } from './CompositionAPI.js'; export default { data() { return { user: user }; }, created() { fetchUser(); } }

In this example, we have a UserComponent.vue component that fetches and displays the authenticated user’s data using the user and fetchUser functions from the CompositionAPI.js file.

By following these steps, you can install Vue.js in your Laravel project and set up authentication using Laravel Sanctum and the Vue Composition API. This will allow you to build a secure and modern web application with a powerful frontend and backend technology stack.