Skip to content
Guest
Laravel · Course Syllabus Show lessons
Security & APIs · 8 min read · Intermediate

Building REST APIs with Resources & Sanctum

Shape predictable JSON responses with API Resources and issue scoped bearer tokens with Laravel Sanctum.

What you'll learn

  • Transform Eloquent models cleanly using `JsonResource` collections
  • Issue and revoke API tokens with `Laravel Sanctum` (`$user->createToken('mobile')`)
  • Apply `throttle:60,1` rate limiting on public API routes

Overview

Shape predictable JSON responses with API Resources and issue scoped bearer tokens with Laravel Sanctum.

Code Example

<?php
namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class CourseResource extends JsonResource {
    public function toArray(Request $request): array {
        return [
            'id' => $this->id,
            'slug' => $this->slug,
            'title' => $this->title,
            'lessonsCount' => $this->whenCounted('lessons'),
        ];
    }
}

Key Takeaways

  • Transform Eloquent models cleanly using JsonResource collections
  • Issue and revoke API tokens with Laravel Sanctum ($user->createToken('mobile'))
  • Apply throttle:60,1 rate limiting on public API routes

Quick Check

Check Your Understanding

Score: 0 / 1

1. What is the main advantage of returning `new UserResource($user)` instead of `return $user` from an API endpoint?

Study Workspace

Finished this lesson?

Your progress is saved locally in your browser, no account needed.

Search courses, lessons, and references

Type to search across all courses, lessons, and quick references.

Press Esc to close Powered by Pagefind