You are currently viewing Building APIs with Laravel: A Simple Guide with Sanctum,Controllers & Resources

Building APIs with Laravel: A Simple Guide with Sanctum,Controllers & Resources

Laravel makes building APIs smooth and elegant — no complex boilerplate, no extra headache. Whether you’re creating a backend for a mobile app or a headless frontend, Laravel gives you everything out of the box. Let’s break down how it works using simple terms and code examples.


?️ 1. Sanctum: Simple Token Authentication for APIs

Laravel Sanctum is a lightweight package that lets you authenticate users using API tokens. Unlike Passport, it’s simpler and perfect for single-page apps (SPA) or mobile apps.

? Installation:

bashCopyEditcomposer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate

? Setup Middleware:

In app/Http/Kernel.php, add this to api middleware group:

phpCopyEdit\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,

In config/sanctum.php, ensure stateful domains are set properly for SPA (skip this for mobile).


? 2. API Authentication Example

You’ll need routes for login, register, and logout.

?️ API Routes (routes/api.php)

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

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

?‍? Controller Example (AuthController)

phpCopyEditpublic 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);
    }

    return response()->json([
        'token' => $user->createToken('api_token')->plainTextToken
    ]);
}

? 3. Using api.php for API Routing

Laravel uses routes/api.php for all API endpoints. It automatically applies the api middleware group, which includes things like rate limiting.

This file is separate from web.php, keeping your API clean and stateless.


? 4. Controller Structure for APIs

API controllers are typically stored under App\Http\Controllers\API.

Here’s how you structure a simple controller for managing products:

bashCopyEditphp artisan make:controller API/ProductController --api

This gives you a RESTful controller with methods like:

  • index() – list all
  • store() – create
  • show() – view one
  • update() – update
  • destroy() – delete

? 5. Resources: Clean API Responses

Laravel Resources let you control the shape of JSON returned by your API. No more leaking internal fields like password or timestamps.

Example Resource:

bashCopyEditphp artisan make:resource ProductResource
phpCopyEditpublic function toArray($request)
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'price' => $this->price,
        'category' => new CategoryResource($this->whenLoaded('category')),
    ];
}

In Controller:

phpCopyEditreturn ProductResource::collection(Product::all());

✅ Summary: Why Laravel APIs Feel Easy

  • ? Sanctum makes authentication fast and token-based
  • ? API routes are neatly organized in api.php
  • ?‍? Controllers give you clean logic separation
  • ? Resources give you beautiful API responses
  • ? Validation, middleware, rate limiting, and Eloquent are all integrated

? Final Thoughts

Laravel’s API tools are not just powerful — they’re also developer-friendly. Whether you’re building your first API or a production-grade backend, Laravel has the pieces to keep your code clean, secure, and efficient.