0

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:

  1. I successfully implemented login using a custom model Karyawan.
  2. Login returns a token, and I can use it with Authorization: Bearer in Postman.

what fails:

  1. When I POST to /transaksi (to create new transaction), I get a 500 Internal Server Error.
  2. Debugging shows that Auth::user() returns null — even though I’m using a valid token in the header.
  3. 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:

  1. Automatically attach id_karyawan from the logged-in user.
  2. Store it inside the transaksi table with other validated data.

Here is some highlight on my code that I suspect:

  1. 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.

  1. 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!

2
  • What is the error reported in the logs for the 500 ? "nstead of return error or debug message, it keeps showing 500." so it is not "Auth::user() returns null" issue. please add the stacktrace for the error to your question. Commented Jul 15 at 10:01
  • 1
    "I'm new to Laravel" and "implemented login using a custom model" - why? Commented Jul 17 at 10:26

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.