Laravel Scout is an official package by Laravel that provides a simple, driver-based solution for adding full-text search to your Eloquent models. It abstracts away the complexities of integrating with various search engines, allowing developers to use a consistent API for searching their application's data.
Purpose and Functionality:
At its core, Scout enables you to make your Eloquent models "searchable." When a model with the `Searchable` trait is created, updated, or deleted, Scout automatically pushes the relevant data to your configured search index. This indexing process can be queued for better application performance.
Key Features:
* Driver-Based: Scout ships with drivers for popular search services like Algolia and MeiliSearch. It also includes a "database" driver for simpler applications or local development. The community provides drivers for other engines like ElasticSearch.
* Automatic Indexing: Seamlessly keeps your search index in sync with your Eloquent models. Any changes to a model are automatically reflected in the search index.
* Configurable: Easily switch between different search drivers by changing an environment variable.
* Customization: Allows you to define precisely which attributes of a model should be pushed to the search index using the `toSearchableArray()` method. You can also override the default index name.
* Queueing: Supports queueing all indexing operations to improve response times for web requests, making the indexing asynchronous.
* Pagination: Integrates smoothly with Laravel's built-in pagination system for search results.
* Eloquent Integration: Search results are returned as Eloquent models, allowing you to continue interacting with them as usual.
Installation Steps:
1. Install the package via Composer: `composer require laravel/scout`
2. Publish the Scout configuration file: `php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"`
3. Configure your desired search driver in your `.env` file (e.g., `SCOUT_DRIVER=algolia`, `SCOUT_DRIVER=meilisearch`, or `SCOUT_DRIVER=database`). If using Algolia or MeiliSearch, you'll also need to configure their API credentials.
Usage Steps:
1. Add the `Searchable` Trait: Include the `Laravel\Scout\Searchable` trait in any Eloquent model you wish to make searchable.
2. Define Searchable Attributes: Optionally, implement the `toSearchableArray()` method in your model. This method should return an array of the data you want to store in your search index. If not implemented, all public properties of the model will be indexed.
3. Perform Searches: Use the `search()` method on your model to query the search index. You can chain additional Eloquent `where` clauses or pagination methods.
4. Import Existing Records: After setting up Scout, you might need to import existing database records into your search index using the Artisan command: `php artisan scout:import "App\Models\YourModel"`
5. Flush Records: To remove all records for a given model from its search index, use: `php artisan scout:flush "App\Models\YourModel"`
Scout simplifies the process of adding powerful search capabilities to your Laravel applications, providing a clean API and flexibility to choose your preferred search engine.
Example Code
```php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;
class Post extends Model
{
use HasFactory, Searchable;
protected $fillable = ['title', 'content', 'published_at'];
/
* Get the indexable data array for the model.
*
* @return array<string, mixed>
*/
public function toSearchableArray(): array
{
// Define which attributes of the Post model should be indexed.
// You can also add computed properties or relationships here.
return [
'id' => $this->id,
'title' => $this->title,
'content' => $this->content,
'published_at' => $this->published_at,
];
}
}
// --- Example Usage (e.g., in a Controller or Route definition) ---
// For this example to work, ensure you have:
// 1. Installed Laravel Scout: `composer require laravel/scout`
// 2. Published the config: `php artisan vendor:publish --provider="Laravel\\Scout\\ScoutServiceProvider"`
// 3. Configured the 'database' driver in your .env (for simplicity, no external services needed):
// `SCOUT_DRIVER=database`
// 4. Run migrations to create a 'posts' table with 'title', 'content', 'published_at' columns.
// 5. Added some test data (e.g., using Post::factory()->count(10)->create();).
// 6. Imported existing records to the search index:
// `php artisan scout:import "App\\Models\\Post"`
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Models\Post;
// Define a route to handle search requests
Route::get('/search', function (Request $request) {
$searchTerm = $request->input('q', ''); // Get search term from query parameter 'q'
// Check if a search term was provided
if (empty($searchTerm)) {
return response()->json(['message' => 'Please provide a search query.'], 400);
}
// Perform the search using the Scout API
// You can chain Eloquent constraints here, like 'where' clauses
$results = Post::search($searchTerm)
->where('published_at', '<=', now())
->paginate(10);
// Prepare data for JSON response
$response = [
'query' => $searchTerm,
'total_results' => $results->total(),
'per_page' => $results->perPage(),
'current_page' => $results->currentPage(),
'last_page' => $results->lastPage(),
'posts' => $results->items()
];
return response()->json($response);
});
// Example of how to trigger the search (e.g., in your browser):
// YourAppUrl/search?q=example
// YourAppUrl/search?q=laravel
// --- Other useful Scout operations (e.g., in an Artisan command or other logic) ---
// To make a model temporarily unsearchable (will remove from index)
// $post = Post::find(1);
// if ($post) { $post->unsearchable(); }
// To make a model searchable again (will add to index if previously unsearchable or not indexed)
// $post = Post::find(1);
// if ($post) { $post->searchable(); }
// To manually flush the entire index for a specific model
// Artisan::call('scout:flush', ['model' => 'App\\Models\\Post']);
// To re-import all records for a model after a change in toSearchableArray()
// Artisan::call('scout:import', ['model' => 'App\\Models\\Post']);
// You can also disable auto-indexing on specific models or during certain operations:
// Post::withoutSyncingToSearch(function () {
// Post::create(['title' => 'Temporary Post', 'content' => 'This post will not be indexed.']);
// });
```








laravel/scout