Laravel Passport Register Login yazıyorum hepsi çalışıyor fakat login ettiğimde 401 hatası alıyorum
Controller
public function register(UserRequest $request) {
$user = User::create($request->validated());
$token = $user->createToken('auth_token')->accessToken;
return response()->json(['token' => $token],201);
}
public function login(UserLoginRequest $request) {
if(!auth()->attempt($request->validated())) {
return response()->json([
'error' => 'Unauthorized'
],401);
}
$token = auth()->user()->createToken('auth_token')->accessToken;
return response()->json([
'token' => $token,
'message' => 'successfull login user'
],200);
}
public function show() {
if(Auth::guard('api')->check()) {
$user = Auth::guard('api')->user();
return response()->json(['user' => $user],200);
}
}
public function logout(Request $request) {
$request->user()->token()->revoke();
response()->json(['message' => 'User logout'],200);
}
Route
middleware(['api', 'return-json']) cevaın json şeklinde dönmesi için middleware
Route::post('/register',[UserController::class, 'register'])->name('register')->middleware(['api', 'return-json']);
Route::post('/login',[UserController::class, 'login'])->name('login');
Route::middleware(['auth:api', 'api', 'return-json'])->group(function() {
Route::get('/show',[UserController::class, 'show'])->name('show');
Route::post('/logout',[UserController::class, 'logout'])->name('logout');
});
auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users'
],
],
User Model
use Laravel\Passport\HasApiTokens;
use HasApiTokens, HasFactory, Notifiable;