Track D · Tutorial 2

Laravel Authentication, Testing & Deployment

Chapter 27 · Backend Specialization
~3 hours Advanced Sanctum · PHPUnit · Forge · Envoyer

Overview

This tutorial extends your Laravel skills with authentication (Sanctum/Passport), testing with PHPUnit, and deployment strategies (Laravel Forge, Envoyer). You will build a secure, tested, and production‑ready API.

Why this matters: Authentication and testing are non‑negotiable for professional applications. Laravel's ecosystem provides first‑class solutions for both.

1. Authentication (Sanctum / Passport)

Laravel Sanctum (API Tokens)

composer require laravel/sanctum php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider" php artisan migrate
// config/sanctum.php – configure token abilities 'abilities' => [ 'products:create' => 'Create products', 'products:delete' => 'Delete products', ]
// User model use Laravel\Sanctum\HasApiTokens; class User extends Authenticatable { use HasApiTokens; } // Create token $token = $user->createToken('auth-token', ['products:create'])->plainTextToken;
// Protecting routes Route::middleware('auth:sanctum')->group(function () { Route::resource('products', ProductController::class); });

Laravel Passport (OAuth2)

For OAuth2, use Passport. It provides full OAuth2 server implementation.

2. Testing with PHPUnit

Laravel uses PHPUnit for testing. Write tests in the tests/ directory.

// tests/Unit/ProductTest.php class ProductTest extends TestCase { use RefreshDatabase; /** @test */ public function it_can_create_a_product() { $product = Product::factory()->create(['name' => 'Laptop']); $this->assertDatabaseHas('products', ['name' => 'Laptop']); } }
// tests/Feature/ProductApiTest.php class ProductApiTest extends TestCase { use RefreshDatabase; /** @test */ public function it_can_list_products() { $response = $this->getJson('/api/products'); $response->assertStatus(200); } }

Run tests with php artisan test or ./vendor/bin/phpunit.

3. Deployment

Laravel Forge (Server Management)

  • Provision servers (AWS, DigitalOcean, etc.)
  • Deploy with Git integration
  • Manage SSL, queues, cron jobs

Laravel Envoyer (Zero‑Downtime Deployment)

  • Atomic deployments
  • Rollback capabilities
  • Environment management

Manual Deployment (Git + Composer)

git pull origin main composer install --no-interaction --prefer-dist --optimize-autoloader php artisan migrate --force php artisan config:cache php artisan route:cache php artisan view:cache

4. API Resources

API Resources transform models into JSON responses with control over fields.

php artisan make:resource ProductResource
// ProductResource.php class ProductResource extends JsonResource { public function toArray($request) { return [ 'id' => $this->id, 'name' => $this->name, 'price' => $this->price, 'created_at' => $this->created_at->toIso8601String(), ]; } } // In controller return ProductResource::collection($products);

Quiz

Question 1

Which Laravel package is recommended for simple API token authentication?

  • Laravel Passport
  • Laravel Sanctum
  • Laravel Socialite
  • Laravel Cashier
Show answer
B. Laravel Sanctum.

Question 2

Which command runs Laravel tests?

  • php artisan test
  • php artisan run:test
  • php artisan phpunit
  • php artisan test:run
Show answer
A. php artisan test.

Question 3

Which tool is used for zero‑downtime deployments with Laravel?

  • Laravel Forge
  • Laravel Envoyer
  • Laravel Vapor
  • Laravel Nova
Show answer
B. Laravel Envoyer.

Exercises

Exercise 1

Add Sanctum authentication to the Blog from Tutorial 1. Protect the create, edit, and delete operations.

Sample answer
  • Install Sanctum and run migrations.
  • Add auth:sanctum middleware to routes.
  • Create login/register endpoints that return a token.
  • Use the token in the Authorization header for requests.

Exercise 2

Write a PHPUnit test for the POST /api/products endpoint that verifies a product is created.

Sample answer
/** @test */ public function it_can_create_a_product_via_api() { $user = User::factory()->create(); $token = $user->createToken('test')->plainTextToken; $response = $this->withHeaders(['Authorization' => 'Bearer ' . $token]) ->postJson('/api/products', ['name' => 'Laptop', 'price' => 999]); $response->assertStatus(201); $this->assertDatabaseHas('products', ['name' => 'Laptop']); }

Homework

Homework 1

Extend the Blog API from Tutorial 1 with Sanctum authentication and API Resources. Ensure all endpoints are tested with PHPUnit.

Sample outline
  • Authentication: Login/Register endpoints returning tokens.
  • Resources: PostResource, CategoryResource.
  • Routes: Protect POST, PUT, DELETE with auth:sanctum.
  • Tests: Test each endpoint with authentication.

Mini‑Project

E‑Commerce API with Sanctum

Build a complete e‑commerce API with:

  • User registration and login (Sanctum)
  • Product CRUD (authenticated)
  • Shopping cart (CRUD)
  • Order creation with inventory check
  • PHPUnit tests for all endpoints
  • API Resources for consistent JSON responses
Sample outline
  • Models: User, Product, Cart, CartItem, Order, OrderItem
  • Controllers: AuthController, ProductController, CartController, OrderController
  • Routes: API routes with Sanctum middleware
  • Tests: Feature tests for each controller
  • Resources: ProductResource, CartResource, OrderResource

Tutorial Summary

You secured Laravel APIs with Sanctum, wrote comprehensive tests with PHPUnit, learned about deployment strategies (Forge, Envoyer), and used API Resources for consistent responses. You now have a complete production‑ready workflow for Laravel development.

Key takeaway: Laravel's ecosystem provides all the tools you need for professional development. From authentication to deployment, Laravel has you covered.