API Authentication Using Laravel 9 Sanctum and Vue js 3 Part 1

1 year ago admin Laravel

In today's tutorial, we are going to see how to create a token-based authentication system using Laravel 9 Sanctum and Vuejs 3.


Create new user

I assume that you have already a new fresh Laravel app and you have already created a database with the migrations we need only one table which is users.

Next inside UserFactory let's update the code like the below:

                                                    
                                                                                                                
<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\User>
 */
class UserFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition()
    {
        return [
            'name' => 'admin',
            'email' => 'user@email.com',
            'email_verified_at' => now(),
            'password' => Hash::make('user12345678'), // password
            'remember_token' => Str::random(10),
        ];
    }

    /**
     * Indicate that the model's email address should be unverified.
     *
     * @return static
     */
    public function unverified()
    {
        return $this->state(fn (array $attributes) => [
            'email_verified_at' => null,
        ]);
    }
}


Seed the user to the database

Next, update the file DatabaseSeeder.php and seed the user to the database, run the command:

php artisan db:seed 

                                                        
                                                                                                                        
<?php

namespace Database\Seeders;

// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        \App\Models\User::factory(1)->create();
    }
}

Create the controller

Next, we add a new controller UserController here we have all the methods that we need.

                                                        
                                                                                                                        
<?php

namespace App\Http\Controllers\Api;

use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;

class UserController extends Controller
{
    //
    public function auth(Request $request){
        //form validation
        $this->validate($request, [
            'email' => 'required|max:255',
            'password' => 'required|min:6|max:255',
        ]);
        //login user
        if(auth()->attempt([
            'email' => $request->email,
            'password' => $request->password
        ])){
            //login success
            $user = User::where('email', $request->email)->first();
            $token = $user->createToken('simple_user')->plainTextToken;
            return response()->json([
                'success' => true,
                'user' => [
                    'currentToken' => $token,
                    'data' => $user
                ]
            ]);
        }else{
            //login fail
            return response()->json([
                'success' => false,
                'message' => 'These credentials do not match any of our records.'
            ]);
        }
    }

    public function logout(){
        auth()->user()->tokens()->delete();
        return response()->json([
            'success' => true,
            'message' => 'Logged out successfully'
        ]);
    }
}


Add vue js 3 and install the packages

Next, we will add Vuejs 3 to our project follow this link to do that.

Now let's add the packages that we will need:

                                                        
                                                                                                                        
npm install sweetalert2
npm install pinia
npm install vue-router@4

Create the store

The structure of our js folder will be like this:

 > js

        > components

            .....       

        > router

            ......

        > stores

            ......

Inside stores add a new file useAuthStore.js and put inside it the code below.

                                                        
                                                                                                                        
import { defineStore } from 'pinia';


export const useAuthStore = defineStore('auth', {
    state: () => ({ 
        user: '',
        errors: ''
    }),
    getters: {
        getUser: (state) => state.user,
        getErrors: (state) => state.errors,
        getHeaderConfig(state) {
            const config = {
                headers: {
                    "Authorization" : `Bearer ${state.user.currentToken}`,
                    "Accept": "application/json",
                }
            }  
            return config;
        }
    },
    actions: {
        setUser() {
            if (localStorage.getItem('user')) {
                this.user = JSON.parse(localStorage.getItem('user'));
            }
        },
        storeUser(user) {
            localStorage.setItem('user', JSON.stringify(user));
            this.user = user;
        },
        clearStoredData() {
            localStorage.removeItem('user');
            this.user = '';
        },
        setErrors(errors) {
            this.errors = errors;
        },
        clearErrors() {
            this.errors = '';
        }
    },
});

Related Tuorials

How to Prevent the Loop Incrementing Operator from Resetting Back to 1 in the Next Pagination Pages in Laravel

In this lesson, we will see how to prevent the loop incrementing operator from resetting back to 1 i...


How to Logout a User from the Other Devices in Laravel 11

In this lesson, we will see how to logout a user from the other devices in Laravel 11, sometimes you...


How to Logout a User from the Current Device in Laravel 11

In this lesson, we will see how to logout a user from the current device in Laravel 11, sometimes yo...


How to Import Multiple Classes from a Single Namespace in Laravel

In this lesson, we will see how to import multiple classes from a single namespace in Laravel by add...


Laravel 11 Livewire CRUD Application Tutorial Part 2

In the second part of this tutorial, we will display all the tasks on the home page and later we wil...


Laravel 11 Livewire CRUD Application Tutorial Part 1

This tutorial will show us how to create a Laravel 11 Livewire CRUD application. The user can c...


How to Conditionally Include a Blade Template in Laravel

In this lesson, we will see how to conditionally include a blade template in Laravel.Sometimes,...


How to Include a Blade Template Only if it Exists in Laravel

In this lesson, we will see how to include a blade template only if it exists in Laravel.Sometimes,&...


How to Pass a Variable to Include in Laravel

In this lesson, we will see how to pass a variable to include in Laravel. Sometimes, we want to pass...


How to the Get the Previous and Next Posts in Laravel

In this lesson, we will see how to get the previous and next posts in Laravel, sometimes when you ge...