How to Build a REST API with Laravel Sanctum for Beginners

Building a REST API with authentication looks complicated, but Laravel Sanctum makes it simple. Sanctum is a great fit for APIs used by mobile apps or SPA front-ends (Vue/React). T...

How to Build a REST API with Laravel Sanctum for Beginners

Building a REST API with authentication looks complicated, but Laravel Sanctum makes it simple. Sanctum is a great fit for APIs used by mobile apps or SPA front-ends (Vue/React). This article guides you through building an API with token-based login from scratch.

Step 1: Install Sanctum

composer require laravel/sanctum
php artisan migrate

In the latest Laravel versions, Sanctum is automatically ready to use for API tokens without complicated additional configuration.

Step 2: Set Up the User Model

Make sure the User model uses the HasApiTokens trait:

use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
}

Step 3: Create the Register & Login Endpoints

In routes/api.php, register public routes for register and login:

Route::post('/register', [AuthController::class, 'register']);
Route::post('/login', [AuthController::class, 'login']);

Then create the controller. Here is an example login method that generates a token:

public function login(Request $request)
{
    $request->validate([
        'email' => 'required|email',
        'password' => 'required',
    ]);

    $user = User::where('email', $request->email)->first();

    if (! $user || ! Hash::check($request->password, $user->password)) {
        return response()->json(['message' => 'Invalid credentials'], 401);
    }

    $token = $user->createToken('auth_token')->plainTextToken;

    return response()->json([
        'access_token' => $token,
        'token_type' => 'Bearer',
    ]);
}

Step 4: Protect Endpoints with Middleware

Endpoints that require login are wrapped in the auth:sanctum middleware:

Route::middleware('auth:sanctum')->group(function () {
    Route::get('/profile', function (Request $request) {
        return $request->user();
    });
    Route::post('/logout', [AuthController::class, 'logout']);
});

Step 5: Accessing the API with a Token

The client sends the token in the Authorization header on every request to a protected endpoint:

Authorization: Bearer {access_token}
Accept: application/json

Without this header, protected endpoints will return a 401 Unauthorized status.

Step 6: Logout (Delete the Token)

public function logout(Request $request)
{
    $request->user()->currentAccessToken()->delete();
    return response()->json(['message' => 'Logged out successfully']);
}

Important Tips

  • Always send the Accept: application/json header so Laravel returns errors in JSON format, not an HTML page.
  • Use HTTPS in production so the token isn't leaked.
  • For an SPA on the same domain, Sanctum also supports cookie-based authentication.

Conclusion

With Laravel Sanctum, building a token-authenticated REST API takes just five steps: install, add the trait, create the auth endpoints, protect routes with auth:sanctum, and send the token via the Bearer header. From here you can develop an API for a mobile app or a modern front-end. Don't forget to secure it with HTTPS when you deploy.

rest api laravel laravel sanctum api token laravel autentikasi api laravel cara membuat api laravel
Read Also

Here are some related articles that might help expand your knowledge:

Share this article
Back to Blog
🚀 Partner Recommendation

Need Premium Source Code & Business Apps?

Access Laravel applications, POS systems, School Management, Clinic Software, ERP solutions, and ready-to-use premium source code at GudangCode.

GudangCode
  • ✔ Premium Source Code
  • ✔ Ready-to-Use Systems
  • ✔ Lifetime Updates
  • ✔ Lifetime Membership
  • ✔ Daily App Updates
Join Membership →