-
composer.json
Open in GitHub{ // "require": { "php": ">=7.4", // "laravel/sanctum": "^2.6" }, // }
-
app/Models/User.php
Open in GitHubuse Illuminate\Foundation\Auth\User as Authenticatable; use Laravel\Sanctum\HasApiTokens; class User extends Authenticatable { use HasApiTokens; // }
-
app/Services/TokenManager.php
Open in GitHubuse App\Models\User; class TokenManager { public function createToken(User $user, array $abilities = ['*']): NewAccessToken { return $user->createToken(config('app.name'), $abilities); } public function destroyTokens(User $user): void { $user->tokens()->delete(); } // }
-
app/Http/Controllers/API/AuthController.php
Open in GitHubuse App\Services\TokenManager; class AuthController extends Controller { // public function login(UserLoginRequest $request) { $user = $this->userRepository->getFirstWhere('email', $request->email); if (!$user || !$this->hash->check($request->password, $user->password)) { abort(Response::HTTP_UNAUTHORIZED, 'Invalid credentials'); } return response()->json([ 'token' => $this->tokenManager->createToken($user)->plainTextToken, ]); } public function logout() { $this->tokenManager->destroyTokens($this->currentUser); return response()->json(null, Response::HTTP_NO_CONTENT); } }
-
config/auth.php
Open in GitHubreturn [ // 'guards' => [ 'web' => [ 'driver' => 'token-via-query-parameter', 'provider' => 'users', ], 'api' => [ 'driver' => 'sanctum', 'provider' => 'users', ], ], // ];