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

Search API

About this lesson

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

When you're building APIs, one key feature that often gets overlooked is search. So how do you handle search efficiently in your Laravel app? That's what we’ll explore today using TypeSense, a powerful open-source search engine.

Why TypeSense?

There are plenty of third-party options available like Algolia or search engines like ElasticSearch, but TypeSense offers:

  • Real-time search results.
  • Fast indexing.
  • Simplicity in setup for developers.

You can start your search service locally and have full control over how data is indexed and queried. Let’s break down how to integrate TypeSense into your Laravel application using Laravel 11.

Step 1: Install Scout and TypeSense

Before jumping into coding, we need to get the tools set up. First, we’ll use Laravel Scout to handle the search indexing. Laravel Scout provides a great abstraction over various search services, including TypeSense.

Install Scout:

composer require laravel/scout

Publish Scout Configuration:

php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"

Install the TypeSense SDK:

composer require typesense/typesense-php

You can find more about the SDK here.

Configure Scout to use TypeSense by adding this to your .env file:

SCOUT_DRIVER=typesense

Step 2: Define Your Search Schema

Now that you have everything installed, the next step is to define what data should be indexed. In Laravel, we do this by marking a model as "searchable" and defining the fields that will be used in search queries.

Here's an example for a Car model:

use Laravel\Scout\Searchable;

class Car extends Model
{
    use Searchable;

    public function toSearchableArray(): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'model' => $this->model,
            'year' => $this->year,
            'created_at' => $this->created_at,
        ];
    }
}

Step 3: Set Up TypeSense Index

For the search to work, you need to set up a schema in TypeSense. The schema defines what fields are searchable and their data types.

Here’s how you can define the schema:

$client = new \Typesense\Client([
    'api_key' => env('TYPESENSE_API_KEY'),
    'nodes' => [
        [
            'host' => 'localhost',
            'port' => '8108',
            'protocol' => 'http',
        ]
    ]
]);

$client->collections->create([
    'name' => 'cars',
    'fields' => [
        ['name' => 'id', 'type' => 'string'],
        ['name' => 'name', 'type' => 'string'],
        ['name' => 'model', 'type' => 'string'],
        ['name' => 'year', 'type' => 'int32'],
        ['name' => 'created_at', 'type' => 'int64'],
    ]
]);

In the example above, we’re defining fields for a car: id, name, model, year, and created_at. You can adapt this for any other types of entities you need to search for.

Step 4: Implement the Search Logic

Once the schema and data are indexed, the next step is to query TypeSense for search results. Here's an example where we allow users to search cars by name and model:

use App\Models\Car;

Route::get('/cars', function (Request $request) {
    $searchTerm = $request->query('q');
    $cars = Car::search($searchTerm)->get();

    return response()->json($cars);
});

This route listens for GET requests on /cars, searches the Car model for the query term, and returns the results as JSON.

Step 5: Catch Unsuccessful Search Queries

Not every search will return results. Knowing what users are searching for can help you improve your API by adding more data or understanding user behavior. For this, we’ll log unsuccessful queries.

Here’s how to create middleware to log search queries:

php artisan make:middleware SearchLog

In your SearchLog middleware:

public function handle(Request $request, Closure $next)
{
    $response = $next($request);

    $searchTerm = $request->query('q');
    if ($response->getData()->isEmpty()) {
        Log::info("Search term not found: {$searchTerm}");
    }

    return $response;
}

Don’t forget to register the middleware in your Kernel.php.

Step 6: Monitor Searches with TypeSense Analytics

TypeSense offers built-in analytics to help you monitor how your search performs and what users are looking for. You can read more about TypeSense Analytics here.

Step 7: Building a Search Interface

A great search API is one thing, but if your users can’t interact with it properly, it’s useless. You can integrate this into your frontend with JavaScript, Vue.js, or React.js. TypeSense has a TypeSense InstantSearch plugin that you can use with Vue.js or React.js.