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

Cleaning up Laravel

About this lesson

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

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! Laravel already packs a punch with its out-of-the-box features, but why stop there? Let's crank it up a notch by supercharging the project! We'll streamline everything, chop the dead weight, and turn it into a lean, mean API development machine.

1. Organize Routes

Start by organizing the routes to create a more structured and clear setup. Amp up your productivity by creating separate directories for different route types:

  • routes/api/ for API routes
  • routes/web/ for web routes
  • routes/console/ for console commands

Move the relevant route files to their designated directories! We're crafting an API-first application, so let's ditch the web routes. Grab that routes/web.php file and clear it out, removing any unnecessary routes.

Example: Removing Web Prefix

By default, Laravel prefixes API routes with /api. Want to remove this prefix and make it a truly API-first installation? Easy! Just dive into the bootstrap/app.php file and set an empty string for the API prefix:

return Application::configure(
    basePath: dirname(__DIR__),
)->withRouting(
    api: __DIR__.'/../routes/api/routes.php',
    commands: __DIR__.'/../routes/console/routes.php',
    apiPrefix: '',
    health: '/up',
);

Great news! Now, your API routes are super easy to access directly, no more /api prefix needed.

2. Encapsulate Routes and Clean Up Unnecessary Files

Encapsulate routes by properly separating them into relevant files. For example, keep your authentication routes in routes/api/auth.php and other API routes in routes/api/routes.php. This keeps your routes organized and avoids clutter.

Become a routing guru! Keep your routes clean and organized by separating them into dedicated files. Boom! Authentication routes? They belong in routes/api/auth.php. Other API routes? Drop them in routes/api/routes.php. Say goodbye to clutter and hello to an organized codebase!

Eliminate unused controllers and files that don't contribute to the API's functionality! If there are any abstract controllers or unnecessary classes, get rid of them to keep the codebase lean and mean.

3. Adjust Authentication Setup

Laravel's default authentication setup might be too restrictive for an API-only project. By moving the auth routes to routes/api/auth.php and ditching them from web/routes.php, you may run into some issues due to Laravel Sanctum's dependence on web routes for handling authentication tokens.

To fix this, make sure your web/routes.php file is all set up with the basic web authentication configuration:

Route::middleware(['web'])->group(static function (): void {
    // Web routes for authentication
});

This setup is necessary for Laravel Sanctum to properly handle token-based authentication.

4. Optimize Database Structure

When building an API, steer clear of auto-incrementing integer IDs for primary keys. These can unintentionally reveal sensitive data and leave your API open to enumeration attacks. Instead, harness the power of ULIDs for a robust and secure solution!

Adjust the users migration file to use ULIDs:

$table->ulid('id')->primary();

In the User model, use a trait to handle UUID generation:

use Illuminate\Support\Str;

class User extends Authenticatable
{
    use HasFactory;
    use HasUlids;
}

This will automatically assign a ULID to new users, enhancing security.

5. Clean Up Factories and Migrations

In your factories and migrations, keep them sharp and focused! Strip out any unnecessary placeholders or comments. Use named parameters in factory definitions to make everything clearer and more readable!

Organize migration columns logically: group identifiers, properties, timestamps, etc., for better readability.

Example: User Factory Cleanup

public function definition(): array
{
    return [
        'name' => $this->faker->name(),
        'email' => $this->faker->unique()->safeEmail(),
        'email_verified_at' => now(),
        'password' => Hash::make('password'), // default password for testing
        'remember_token' => Str::random(10),
    ];
}

6. Set Up Soft Deletes

Integrate soft deletes to provide users a chance to recover! Perfect for apps where users might accidentally remove their accounts.

use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Authenticatable
{
    use SoftDeletes;
}

Soft deletes give your data a safety net by keeping records in the database for an awesome grace period (like 30 days) before they’re gone for good!

7. Build a Thoughtful Data Model for API Use Cases

Get pumped about your data model! Craft models and migrations that perfectly fit your API’s needs. Let’s say you’re building an awesome ping API:

  • Service Model: Represents the services to be monitored.
  • Check Model: Represents individual checks or pings to services.
  • Credential Model: Handles authentication credentials for services.
  • Report Model: Stores the results of checks.

Each of these models will have exciting migrations and should be brilliantly structured to perfectly support the dynamic use cases of your API.

8. Implement Tests and Ensure Consistency

After restructuring, put your tests to the ultimate challenge to make sure everything's firing on all cylinders! If tests stumble due to changes in route structure or authentication, tackle them head-on and ensure your API is rocking and rolling perfectly!

php artisan test

If any issues arise, tackle them head-on and tweak those configurations to keep your application running smoothly and performing like a champ!

9. Avoid Premature Optimization

It's thrilling to dive into optimization, but remember - jumping in too soon can cause headaches. Make changes step-by-step and test rigorously to ensure they deliver genuine performance boosts without creating new issues.

10. Maintain a Clean Codebase

Adopt the awesome habit of cleaning up any code you come across! Get rid of unused code, streamline logic, and amp up readability. These small tweaks will power up your project, making it cleaner and way more maintainable in the long run.

By following these principles, you'll supercharge your Laravel setup for API-first development, turbocharging performance, fortifying security, and enhancing maintainability!