Skip to content

Laravel Scout

Nguồn gốc: Bản dịch từ Laravel Scout

Giới thiệu (Introduction)

Laravel Scout cung cấp giải pháp full-text search đơn giản, driver-based cho Eloquent models. Sử dụng model observers, Scout tự động giữ search index đồng bộ với bản ghi Eloquent.

Hiện tại Scout hỗ trợ: Algolia, Meilisearch, Typesense và MySQL/PostgreSQL (database driver).

Cài đặt (Installation)

bash
composer require laravel/scout

Publish config:

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

Driver Prerequisites

  • Algolia: composer require algolia/algoliasearch-client-php
  • Meilisearch: composer require meilisearch/meilisearch-php
  • Typesense: composer require typesense/typesense-php

Cấu hình (Configuration)

Configuring Model Indexes

Thêm trait Searchable vào model:

php
use Laravel\Scout\Searchable;

class Post extends Model
{
    use Searchable;
}

Configuring Searchable Data

Override toSearchableArray() để tùy chỉnh dữ liệu index:

php
public function toSearchableArray(): array
{
    return [
        'id' => $this->id,
        'title' => $this->title,
        'content' => $this->content,
    ];
}

Configuring the Model ID

Mặc định dùng primary key. Override bằng getScoutKey().

Indexing

Batch Import

bash
php artisan scout:import "App\Models\Post"

Adding Records

Tạo/cập nhật model → Scout tự động cập nhật index.

Updating Records

Gọi save() → Scout tự cập nhật.

Removing Records

Xóa model → Scout tự xóa khỏi index.

Pausing Indexing

php
Post::withoutSyncingToSearch(function () {
    // Thao tác model không sync lên search...
});

Conditionally Searchable

Override shouldBeSearchable() để kiểm soát khi nào model được index.

Searching

php
$orders = Order::search('Star Trek')->get();

Where Clauses

php
$orders = Order::search('Star Trek')
    ->where('user_id', 1)
    ->get();

Pagination

php
$orders = Order::search('Star Trek')->paginate();

Soft Deleting

Scout hỗ trợ tìm kiếm model đã soft delete.

Custom Engines

Tự tạo search engine driver.