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

Cache Requests

About this lesson

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

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. Let’s understand HTTP cache headers and how to implement them for specific routes, ultimately ensuring that your Laravel API is more efficient and responsive.

Why Caching Matters

Caching allows us to store responses for later use, which saves on repetitive database queries and reduces server load. This translates to faster response times and a better experience for users. Let's take a practical look at how to set up caching in Laravel using HTTP cache headers.

Step 1: Configuring HTTP Cache Headers in Laravel

First, head over to the Laravel documentation on caching to familiarize yourself with the basic configuration options. Laravel provides several cache headers like max-age and E-tag, which are essential for controlling how long content is cached and whether it needs to be updated.

For example:

  • max-age: Specifies the maximum amount of time a resource is considered fresh.
  • E-tag: An identifier used to determine if a resource has been modified.

Step 2: Defining What to Cache

Now, let’s focus on defining what parts of our API need caching.

Typically, you'd want to cache data-heavy endpoints like GET requests for index and show routes, as they are the most accessed. In contrast, actions like POST, PUT, or DELETE are less suited for caching, as they modify data.

Here’s a quick breakdown of routes to cache:

  • Index (GET): Cache this since it's likely a heavy request.
  • Show (GET): Also a good candidate for caching.
  • Create, Update, Delete (POST, PUT, DELETE): Not suitable for caching since these routes change data.

You can easily group these caching rules using Laravel’s middleware, which allows fine control over which routes are cached and how long they are cached.

Step 3: Adding Cache Headers

Adding cache headers to your Laravel routes is as simple as adding the necessary middleware to your routes or controllers. Here’s an example of how you can apply cache headers:

Route::middleware(['cache.headers:public;max_age=600'])->group(static function (): void {
    Route::get('/posts', 'PostController@index');
    Route::get('/posts/{post}', 'PostController@show');
});

In this example, we are telling Laravel to cache responses for GET requests to the posts index and show endpoints, for up to 600 seconds.

Step 4: Overcoming Cache Conflicts

When applying caching, it’s important to ensure that caching doesn’t interfere with other functionalities. For instance, if a POST request is being called before a GET request on the same resource, you may encounter unexpected behavior.

To resolve this, you can ensure that specific routes are cached in the correct order by adjusting the route registration, ensuring the most commonly called routes, such as POST, are registered first.

Step 5: Private vs. Public Caching

While caching is fantastic for improving performance, it’s important to understand the distinction between private and public caches.

In most cases, you’ll want to use private caching, especially for authenticated API requests where responses should be personalized.

You can set the cache as private like this:

Route::middleware(['cache.headers:private;max_age=300'])->group(static function (): void {
    Route::get('/user/profile', 'UserController@profile');
});

This ensures that the cache is specific to the authenticated user.

Step 6: Leveraging Laravel Cache Packages

For more advanced caching strategies, you can explore using third-party packages. One highly recommended package is Spatie’s Laravel Response Cache, which simplifies response caching by allowing you to cache entire responses with minimal configuration.

To get started with this package, install it using Composer:

composer require spatie/laravel-responsecache

After installation, you can publish the configuration file:

php artisan vendor:publish --provider="Spatie\ResponseCache\ResponseCacheServiceProvider"

Once installed, the package allows you to cache entire responses effortlessly. For example:

use Spatie\ResponseCache\Facades\ResponseCache;

Route::get('/posts', function () {
    return ResponseCache::cacheForever();
});

Step 7: Adding Cloudflare for Enhanced Caching and Security

To take your caching strategy to the next level, consider using a CDN like Cloudflare.

By adding a CDN in front of your Laravel API, you not only enhance caching but also add a layer of security with features like DDoS protection and a Web Application Firewall (WAF).

Cloudflare can cache responses at the edge, reducing latency for users across the globe. This, combined with Laravel’s caching, ensures your API is both fast and secure.

Step 8: Fine-Tuning Your Cache Configuration

Laravel gives you the flexibility to fine-tune your cache configuration.

For instance, you can specify different cache lifetimes for different resources, set cache profiles for successful GET requests, or even bypass caching under specific conditions. For more information on fine-tuning your caching setup, visit the Laravel Cache Docs.

Wrapping Up

With Laravel 11 and the right caching strategy, you can significantly boost the performance of your API. Let’s move on to the next topic, where we’ll explore another vital aspect of optimizing APIs in Laravel.