API Authentication Using Laravel Sanctum and React js Part 1
In today's tutorial, we are going to see how to create a token-based authentication system using Laravel 10 Sanctum and React JS, in this first part we will handle the backend (seeding the database creating the controller, and the routes).
Create new user
I assume that you have already a new fresh Laravel app and you have already created and migrated the database, we need only one table which is users.
Next inside UserFactory let's update the code to create a new user.
<?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' => 'user',
'email' => 'user@email.com',
'email_verified_at' => now(),
'password' => Hash::make('user1234'), // 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' Inside we have all the methods that we need.
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
class UserController extends Controller
{
//
public function store(Request $request)
{
$request->validate([
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email','max:255', 'unique:users'],
'password' => ['required', 'min:8','max:255'],
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password)
]);
return response()->json([
'user' => $user,
'access_token' => $user->createToken('new_user')->plainTextToken,
]);
}
public function auth(Request $request)
{
$request->validate([
'email' => ['required', 'string', 'email','max:255'],
'password' => ['required', 'min:8','max:255'],
]);
$user = User::whereEmail($request->email)->first();
if(!$user || !Hash::check($request->password, $user->password)) {
return response()->json([
'error' => 'These credentials do not match any of our records'
]);
}
return response()->json([
'user' => $user,
'access_token' => $user->createToken('new_user')->plainTextToken,
]);
}
public function logout(Request $request)
{
$request->user()->currentAccessToken()->delete();
return response()->noContent();
}
}
Add routes
Next, we will add routes inside the 'api.php' file.
Route::middleware('auth:sanctum')->group(function() {
Route::get('user', function (Request $request) {
return [
'user' => $request->user(),
'currentToken' => $request->bearerToken()
];
});
Route::post('user/logout', [UserController::class, 'logout']);
});
Route::post('user/register', [UserController::class, 'store']);
Route::post('user/login', [UserController::class, 'auth']);