Laravel API Course

1. Intro & Setup

Welcome to the Laravel API course! Get ready to dive into the exciting world of building APIs with Laravel, the powerful and flexible PHP framework.

15:57

2. Cleaning up Laravel

Ready to supercharge your Laravel project for an API-first approach? Let’s dive into optimizing and cleaning it up to make it lightning-fast and ultra-efficient!

16:19

3. Data Modeling

When building an API, mastering the art of structuring your data and defining dynamic relationships between various entities is absolutely essential in Laravel 11.

24:27

4. API Design

When you design an API, it’s absolutely crucial to understand that every API should have a meaningful purpose!

33:09

5. Authentication & Authorization

Say goodbye to the hassle of manually crafting every single detail, and say hello to a streamlined, efficient process that keeps your endpoints vividly documented and ready to go!

14:15

6. Rate Limiting

When it comes to managing API requests, rate limiting is a key player. You don’t want to open the floodgates and let users bombard your API with endless requests.

8:24

7. API Versioning

API versioning might sound like a minor detail at first, but trust me, it's one of those decisions that can make or break the future usability of your API.

22:22

8. Pagination

When you're handling requests that could return extensive lists of resources, it's essential to implement pagination to ensure your responses are manageable and user-friendly.

11:43

9. API Standards

API standards, while useful, aren’t the be-all and end-all. What often takes precedence is discoverability and consistency in your API design.

26:17

10. Handling Errors

Today, we'll explore how to leverage Laravel 11’s error handling system by implementing the API Problem Specification and enhancing it with custom packages to provide consistent, informative error responses.

26:49

11. Write Operations

Let’s explore the steps to manage resources in a Laravel 11 API, focusing on creating, validating, updating, and deleting resources. We’ll use a real-world approach to ensure clarity and usability.

29:30

12. Internationalization

In our previous video, we dove deep into handling write operations—everything from data validation and authorization to deciding between synchronous and asynchronous processing.

11:44

13. Caching Data

In our previous video, we dove deep into handling write operations—everything from data validation and authorization to deciding between synchronous and asynchronous processing.

18:08

14. Basic Security

When it comes to API security, think of it not as a threat but as an opportunity—a chance to build robust, multilayered defenses around your API.

9:53

15. Cache Requests

In Laravel 11, we can take advantage of built-in HTTP features to manage our cache more effectively, streamlining both the response time and the overall user experience.

8:40

16. Scheduling tasks & Sending requests

When working on a Laravel API, the task scheduling system plays a significant role in automating background jobs.

40:33

17. Notifications

Whether you're building a ping service or any application that requires user communication, you’ll likely need to notify users when certain actions occur, such as a service failure.

15:57

18. Monitoring and Logging

When you're developing APIs, it's important to have a clear picture of how your API is performing in real-time.

21:33

19. Testing

When you're developing APIs or any web-based product using Laravel 11, testing plays a crucial role in ensuring that your application behaves as expected.

18:01

20. API Platform

When it comes to building web applications, Laravel has long been a go-to framework for many developers. It's a robust framework, especially for full-stack applications.

17:16

21. Feature Flags

When it comes to building web applications, Laravel has long been a go-to framework for many developers. It's a robust framework, especially for full-stack applications.

11:05

22. Web Sockets

When you're working with APIs, there's a common misconception that WebSockets aren't relevant.

9:58

23. Search API

When you're building APIs, one key feature that often gets overlooked is search. That's what we’ll explore today using TypeSense(https://typesense.org/), a powerful open-source search engine.

15:30

24. Documenting your API

By default, API Platform will give you an OpenAPI specification (currently version 3.1). This standard format allows your API to be easily understood by machines and developers alike.

07:06

Want an easy-to-use API Observability Tool? Try Treblle now

Data Modeling

About this lesson

When building an API, mastering the art of structuring your data and defining dynamic relationships between various entities is absolutely essential in Laravel 11.

24:27 October 4, 2024

When building an API, mastering the art of structuring your data and defining dynamic relationships between various entities is absolutely essential in Laravel 11. In this exciting section, we're diving into the setup of data models for an API in Laravel 11! Get ready to master authentication, amplify user services, secure credentials, and conquer monitoring checks like a pro! Get ready to dive into actionable tips for building powerful relationships, mastering seamless migrations, and supercharging your Laravel app for real-world awesomeness!

Setting Up Token-Based Authentication

For this API, token-based authentication is an absolute game-changer! It's super secure, effortlessly stateless, and works like magic for microservices or web apps. In Laravel 11, polymorphic relationships bring authentication tokens to life with fields like tokenable_id and tokenable_type! By default, tokenable_id is an integer, but for a supercharged, globally distributed system, switch to ULIDs for maximum awesomeness! To update the migration, modify the morphs method to use ULID:

$table->ulidMorphs('tokenable');

Stay on top of your tokens! With Laravel 11, you can now supercharge your token management by shifting them to a dedicated table. Take control effortlessly!

Defining the Service Model

In the context of APIs, a service is a dynamic web app or microservice that's actively engaging with your main Laravel app. Here’s how you can set up a Service model in Laravel 11:

Add a User Association:

$table->foreignUlid('user_id')->index()->constrained('users')->onDelete('cascade');

This guarantees that every service is uniquely linked to an individual user!

Define Service Attributes:

  • name: A human-readable name for easy reference.
  • url: The base URL for the service (e.g., api.treblle.com). Structuring services like this provides a clear approach to managing microservices and their statuses.

Creating a Service Factory

Alright, the model is set up! Time to work some magic and create a factory to churn out awesome, fake data for testing. Thanks to the handy PHP Faker library, this is going to be a breeze.

Define Factory Structure:

return [
    'name' => $this->faker->company(),
    'url' => $this->faker->unique()->url(),
    'user_id' => User::factory(),
];

Customize your fake data to maintain context and relevance for your tests.

Managing API Credentials

API credentials are crucial for secure communication! Ready to model them in Laravel 11? Let’s do this:

Structure Your Credentials:

Schema::create('credentials', function (Blueprint $table): void {
    $table->ulid('id')->primary();
    $table->string('name');
    $table->text('value');
    $table->json('metadata')->nullable();
    $table->foreignUlid('user_id')->index()->constrained('users')->cascadeOnDelete();
});

Each credential should have a name, a secure value, and optional metadata (e.g., header type).

Implement Encryption:

protected $casts = [
    'value' => 'encrypted',
    'metadata' => 'json',
];

This will store credentials securely by encrypting them in the database.

Factory Setup:

return [
    'name' => $this->faker->company(),
    'value' => Str::random(),
    'metadata' => null,
];

Creating Relationships Between Models

Relationships are crucial in turbocharging the connections between various entities in your API!

Service to User:

public function user(): BelongsTo
{
    return $this->belongsTo(
        related: User::class,
        foreignKey: 'user_id',
    );
}

User to Service:

public function services(): HasMany
{
    return $this->hasMany(
        related: Service::class,
        foreignKey: 'user_id',
    );
}

This setup allows efficient retrieval and management of data between users and services.

Setting Up Checks for API Monitoring

Keep Your APIs Running Smoothly! Here's How to Set Up API Checks in Laravel 11:

Define a Check Model:

Schema::create('checks', function (Blueprint $table): void {
    $table->ulid('id')->primary();

    $table->string('name');
    $table->string('path');
    $table->foreignUlid('service_id')->index()->constrained('services')->cascadeOnDelete();
});

A "check" is an HTTP request zipping off to an endpoint to ensure it's up and running!

Create a Check Factory:

return [
    'name' => $this->faker->word(),
    'path' => $this->faker->url(),
];

Add Additional Features:

  • Custom Headers: Include custom headers for checks.
  • JSON Parameters: Enable JSON payloads for dynamic request setups.

By setting up API checks, you create a vibrant, dynamic system for ensuring top-notch reliability and peak performance. In this exciting overview, we've explored everything from kickstarting authentication, defining dynamic services, juggling credentials, and supercharging API monitoring checks!