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 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...


How Do you Format a Number as K/M/B in Laravel

In this lesson, we will see how to format a number as K/M/B in Laravel, sometimes we want to display...


How to Override Laravel Fortify Default Registration Redirect

In this lesson, we will see how to override Laravel Fortify default registration redirect, sometimes...


How to Override Laravel Fortify Default Login Redirect

In this lesson, we will see how to override Laravel Fortify default login redirect, sometimes when w...


How to Use the Same Validation Form Request for both Create and Update in Laravel

In this lesson, we will see how to use the same validation form request for both create and update i...


How to Get Raw SQL Output from the Eloquent Model in Laravel 11

In this lesson, we will see how to get raw SQL output from the eloquent model in Laravel 11, sometim...


How to Check if a Record Does Not Exist in Laravel

in this lesson, we will see how to check if a record does not exist in laravel, sometimes you need t...