Phase 6 · Laravel MasteryModule 37~58 min read

Authentication & APIs in Laravel

Implement identity, policies, token-secured APIs, resources, rate limits, and safe account workflows.

What you'll learn

Secure browser and token clients using Laravel's authentication ecosystem without confusing identity with permission. Policies protect resources, Sanctum scopes tokens, API Resources shape output, and rate limits reduce abuse.

By the end of this lesson, you'll be able to:

  • Apply gates and policies to resources
  • Issue and constrain API tokens
  • Build safe API Resources and rate limits

Core mental model

Professional PHP is less about memorizing APIs and more about choosing a clear boundary for each responsibility. Use this table as a decision guide while reading the examples.

ConceptWhat it protectsDecision rule
GuardAuthentication mechanismChoose session or token identity for the client type.
PolicyResource authorizationCentralize actor/action/resource rules.
API ResourceStable representationExpose a deliberate public shape and conditional relations.

Professional workflow

Build the feature in small, verifiable steps. Each step leaves the system in a state you can test.

  1. Describe the Laravel identity and API boundary boundary: its inputs, outputs, invariants, and expected failures.
  2. Implement the smallest happy path behind an explicit contract.
  3. Add validation and translate low-level failures into language the caller understands.
  4. Exercise the boundary with realistic data, then inspect output, logs, and resource cleanup.
  5. Refactor only after behavior is protected by a repeatable check.

Make the boundary visible

Name inputs, outputs, side effects, and failure cases before adding framework or infrastructure code. That habit keeps advanced PHP understandable as the application grows.

Guided code lab

Authorize at the resource

The policy considers ownership and role; the controller invokes the same named rule everywhere.

CoursePolicy.php
<?php
final class CoursePolicy
{
    public function update(User $user, Course $course): bool
    {
        return $user->is_admin || $course->author_id === $user->id;
    }
}

// Controller:
$this->authorize('update', $course);

Secure and shape the API route

Sanctum authenticates the token, ability middleware limits intent, and the resource owns output.

routes/api.php
<?php
Route::middleware(['auth:sanctum', 'abilities:courses:write'])
    ->patch('/courses/{course}', UpdateCourseController::class);

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

Production practice

Contract

Authenticate the caller, authorize the resource action, validate the command, then serialize only approved output.

Verification

Test unauthenticated, wrong-token-ability, wrong-owner, rate-limited, revoked-token, and successful paths.

Operations

Hash tokens at rest, expire and revoke them, monitor failed authentication, and rate-limit by meaningful identity.

Common failure mode

Hiding an Edit button is user experience, not authorization. A client can call the endpoint directly unless the server policy denies it.

Independent workshop

Expose a Sanctum-protected author API with scoped tokens, course policies, resources, password confirmation, and abuse controls.

Your finished workshop must include:

  • Authentication and token lifecycle
  • Policies plus negative feature tests
  • Resource collection with pagination and rate-limit headers

Definition of done

Run the happy path and at least two failure paths, explain one design tradeoff in a short README, and leave the code formatted and ready for review.

Recap & quick check

Key takeaways

  • Authentication answers who; authorization answers may they.
  • Policies centralize resource rules.
  • Token abilities reduce granted power.
  • API Resources prevent accidental data exposure.

Quick check

1. What decides whether a user may update one course?

2. What limits a token to selected capabilities?

3. Where should private model fields be excluded?

Keep the workshop: later phases deliberately build on these boundaries, so today's small example can become part of your portfolio architecture.