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

Caching Data

About this lesson

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 October 4, 2024

When we talk about building efficient APIs, it’s not just about fetching data from the database and sending it back to the user. Performance is a huge factor that can’t be overlooked, and it’s more complex than a simple "one-size-fits-all" solution. You need to think in layers, and caching is often the first layer to address when optimizing an API.

Step 1: Implementing Cache with Redis in Laravel 11

Let’s dive into caching using Redis, a popular choice among Laravel developers. Before jumping into the code, ensure you have the PHP Redis extension installed. Alternatively, you can use the predis/predis package if you prefer. To get started, run:

composer require predis/predis

This command pulls in the Redis package, setting you up to begin caching data. Once installed, you’ll need to update your .env file to configure Redis.

Configuration in .env File

REDIS_HOST=localhost
REDIS_PASSWORD=null
REDIS_PORT=6379

With Redis set up, configure Laravel to use Redis as its cache driver by updating the config/cache.php file to reflect this.

Step 2: Structuring Cache Keys for Better Performance

Building a robust API requires organizing your cache keys effectively. A common strategy is caching data that doesn’t change frequently, such as user-specific services, while using dynamic keys based on user identifiers.

Here’s where Laravel 11’s enums come in handy. By defining a static cache key enum, you can make your cache management simpler.

enum CacheKey: string
{
    case USER_SERVICES = 'user_services';
}

With this, you can cache services for a specific user like this:

$cachedServices = Cache::rememberForever(
    key: CacheKey::USER_SERVICES->value . Auth::id(),
    value: fn () => Service::where('user_id', Auth::id())->get(),
);

Why Cache Forever?

Since services don’t change frequently, it makes sense to cache them indefinitely. The key here is to invalidate the cache when the data changes (for example, when a new service is added, updated, or deleted). This way, your cache stays up-to-date without needing to rely on expiration policies that could slow down your API.

Step 3: Invalidating Cache with Observers

Cache invalidation is just as important as caching itself. In Laravel 11, you can use observers to handle this. Observers listen to events like created, updated, and deleted, allowing you to automatically invalidate cache when necessary.

Creating the Observer

First, create the observer by running the following Artisan command:

php artisan make:observer ServiceObserver

In the observer, you’ll write logic to invalidate the cache whenever a service is modified:

final class ServiceObserver
{
    public function created(Service $service): void
    {
        Cache::forget(CacheKey::USER_SERVICES->value . $service->user_id);
    }

    public function updated(Service $service): void
    {
        Cache::forget(CacheKey::USER_SERVICES->value . $service->user_id);
    }

    public function deleted(Service $service): void
    {
        Cache::forget(CacheKey::USER_SERVICES->value . $service->user_id);
    }
}

Registering the Observer

To ensure that the observer is properly connected to your service model, you’ll need to register it in the model:

#[ObservedBy(classes: ServiceObserver::class)]
final class Service extends Model
{
}

From here, anytime a service is created, updated, or deleted, the cache will automatically be invalidated, ensuring that the latest data is always being served.

Step 4: Caching Route Model Binding for a Performance Boost

Laravel 11’s route model binding is incredibly convenient, but it can sometimes introduce performance bottlenecks, especially when dealing with large datasets. Instead of fetching a service from the database each time a route is accessed, you can cache it using Redis. Here’s an example:

$service = Cache::rememberForever(
    CacheKey::SERVICE->value . $serviceId,
    Service::findOrFail($serviceId),
);

This approach significantly reduces database lookups by leveraging Redis to serve cached data quickly.