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


How to Check if a Record Exists in Laravel

in this lesson, we will see how to check if a record exists in laravel, sometimes you need to check...


How to Decrement Multiple Fields in Laravel

In this lesson, we will see how to decrement multiple fields in Laravel, in the old versions of lara...


How to Increment Multiple Fields in Laravel

In this lesson, we will see how to increment multiple fields in Laravel, in the old versions of lara...


How to Use the Same Request Validation Rules for Storing and Updating in Laravel

In this lesson, we will see how to use the same request validation rules for storing and updating in...


How to Go Back to the Previous URL in Laravel Blade

In this lesson, we will see how to go back to the previous URL in Laravel Blade, sometimes we need t...


How to Add Additional Data to The Resource JSON Response in Laravel

In this lesson, we will see how to add additional data to the resource JSON response in Laravel, let...


How to Specify the Attributes to be Returned in the Laravel Find Method

In this lesson, we will see how to specify the attributes to be returned in the Laravel find method,...


How to Get Data Using Where All in Laravel

In this lesson, we will see how to get data using Where All in Laravel, the Where All method is used...


How to Get Data Using Where Any in Laravel

In this lesson, we will see how to get data using Where Any in Laravel, the Where Any method is used...