API Authentication Using Laravel 9 Sanctum and Vue js 3 Part 1
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 = '';
}
},
});