I'm new to Laravel and building a backend API system from scratch using Laravel + Sanctum (no frontend yet, just Postman for now). I'm trying to create a simple authenticated API where each logged-in user (karyawan) can create a "transaksi" (transaction), and their id_karyawan (worker_id) is stored alongside the new record. Here’s what I’ve done so far:
- I successfully implemented login using a custom model Karyawan.
- Login returns a token, and I can use it with Authorization: Bearer in Postman.
what fails:
- When I POST to /transaksi (to create new transaction), I get a 500 Internal Server Error.
- Debugging shows that Auth::user() returns null — even though I’m using a valid token in the header.
- Not even using GET return output. It always showed 500 internal server error. I suspect that's because of the middleware issues.
What I'm trying to do:
When a user is logged in and hits the POST /transaksi endpoint, I want to:
- Automatically attach id_karyawan from the logged-in user.
- Store it inside the transaksi table with other validated data.
Here is some highlight on my code that I suspect:
- The login works but not for logout.
Route::post('/login', [AuthController::class, 'login']); Route::middleware('auth:sanctum')->post('/logout', [AuthController::class, 'logout']);
This return 500.
- Routing for transaction using sanctum too.
Route::middleware('auth:sanctum')->group(function () { Route::get('/transaksi', [TransaksiController::class, 'index']); Route::post('/transaksi', [TransaksiController::class, 'store']);}
3.Here is codes from TransaksiController.php
$user = Auth::user(); if (!$user) { return response()->json([ 'message' => 'Unauthorized - Token tidak valid atau sudah expired', 'debug' => [ 'auth_guard' => config('auth.defaults.guard'), 'header_auth' => $request->header('Authorization'), 'user_check' => Auth::check() ] ], 401); }
Instead of return error or debug message, it keeps showing 500.
Let me know if you want to see:
AuthController (login/logout)
TransaksiController store method
routes/api.php
auth.php
I’ll provide them as needed.
I tried search and read the documentation but still can't figure it out. I'm sorry. Thank you for your help!