composer create-project --prefer-dist laravel/laravel laravel-sanctum-tutorial
composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
}
Route::post('/auth/register', [AuthController::class, 'createUser']);
Route::post('/auth/login', [AuthController::class, 'loginUser']);
Oluşturduktan sonra AuthController içine ilgili methodları tanımladıktan sonra token oluşturma işlemine geçiyoruz.
public function createUser(Request $request)
{
try {
$validateUser = Validator::make($request->all(),
[
'name' => 'required',
'email' => 'required|email|unique:users,email',
'password' => 'required'
]);
if($validateUser->fails()){
return response()->json([
'status' => false,
'message' => 'validation error',
'errors' => $validateUser->errors()
], 401);
}
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password)
]);
$token = $user->createToken(
'token-name', ['*'], now()->addMinutes(2)
)->plainTextToken;
return response()->json([
'status' => true,
'message' => 'User Created Successfully',
'token' => $token
], 200);
} catch (\Throwable $th) {
return response()->json([
'status' => false,
'message' => $th->getMessage()
], 500);
}
}
public function loginUser(Request $request)
{
try {
$validateUser = Validator::make($request->all(),
[
'email' => 'required|email',
'password' => 'required'
]);
if($validateUser->fails()){
return response()->json([
'status' => false,
'message' => 'validation error',
'errors' => $validateUser->errors()
], 401);
}
if(!Auth::attempt($request->only(['email', 'password']))){
return response()->json([
'status' => false,
'message' => 'Email & Password does not match with our record.',
], 401);
}
$user = User::where('email', $request->email)->first();
return response()->json([
'status' => true,
'message' => 'User Logged In Successfully',
'token' => $user->createToken("API TOKEN")->plainTextToken
], 200);
} catch (\Throwable $th) {
return response()->json([
'status' => false,
'message' => $th->getMessage()
], 500);
}
}
Route::get('/get-post', [AuthController::class, 'getPost'])->middleware(["auth:sanctum"]);