To add full-text search to Laravel models, you can use the built-in capabilities of MySQL or PostgreSQL along with the Laravel Scout package, which simplifies the integration of full-text search functionality. Below is a step-by-step guide on how to implement full-text search in your Laravel application.
Step 1: Install Laravel Scout
To get started, first, you need to install Laravel Scout. Run the following command in your terminal:
bash
1 |
composer require laravel/scout |
Step 2: Configure Laravel Scout
After installation, publish the Scout configuration file:
bash
1 |
php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider" |
This will create a config/scout.php
configuration file where you can configure the search driver and other settings.
Step 3: Set Up a Search Driver
By default, Laravel Scout uses the Database driver, but you can use other services like Algolia, MeiliSearch, or TNTSearch. For this guide, we’ll stick with the default Database driver for simplicity.
Open the config/scout.php
file and ensure that the driver is set to database
:
php
1 |
'driver' => 'database', |
Step 4: Add Full-Text Search Index to Your Database
For full-text search to work, you need to create a full-text index on the columns you want to search. For example, if you have a posts
table and you want to search through the title
and body
columns, you can do this by creating a migration:
bash
1 |
php artisan make:migration add_fulltext_index_to_posts_table |
In the migration file, define the full-text index:
php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class AddFulltextIndexToPostsTable extends Migration { public function up() { Schema::table('posts', function (Blueprint $table) { // Add a full-text index on title and body columns $table->fullText('title'); $table->fullText('body'); }); } public function down() { Schema::table('posts', function (Blueprint $table) { // Drop the full-text index $table->dropFullText(['title', 'body']); }); } } |
Run the migration to apply the changes:
bash
1 |
php artisan migrate |
Step 5: Implement Searchable in Your Model
Next, make your model searchable. If you have a Post
model, open app/Models/Post.php
and use the Searchable
trait:
php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Laravel\Scout\Searchable; class Post extends Model { use Searchable; protected $fillable = ['title', 'body']; // Define the searchable attributes public function toSearchableArray() { return [ 'title' => $this->title, 'body' => $this->body, ]; } } |
Step 6: Index Existing Records
To make existing records searchable, you need to index them. You can do this using the scout:import
command:
bash
1 |
php artisan scout:import "App\Models\Post" |
Step 7: Perform a Full-Text Search
Now you can perform full-text searches using the search
method provided by Laravel Scout. For example, to search for posts with the term “Laravel”:
php
1 |
$posts = Post::search('Laravel')->get(); |
You can also chain additional query methods:
php
1 |
$posts = Post::search('Laravel')->where('published', true)->get(); |
Step 8: Display Search Results
In your view, you can display the search results like this:
blade
1 2 3 4 |
@foreach($posts as $post) <h2>{{ $post->title }}</h2> <p>{{ $post->body }}</p> @endforeach |
Step 9: Add Search Form
Create a simple search form to allow users to input their search queries:
blade
1 2 3 4 |
<form action="{{ route('posts.search') }}" method="GET"> <input type="text" name="query" placeholder="Search posts..." required> <button type="submit">Search</button> </form> |
Step 10: Handle Search Requests
In your controller, handle the search request and return the search results:
php
1 2 3 4 5 6 7 8 9 10 11 12 |
use App\Models\Post; class PostController extends Controller { public function search(Request $request) { $query = $request->input('query'); $posts = Post::search($query)->get(); return view('posts.index', compact('posts')); } } |
Step 11: Set Up Routes
Add a route for the search functionality in routes/web.php
:
php
1 2 3 |
use App\Http\Controllers\PostController; Route::get('/search', [PostController::class, 'search'])->name('posts.search'); |
Optional: Use Advanced Features
Pagination
To paginate your search results, you can use the paginate
method:
php
1 |
$posts = Post::search('Laravel')->paginate(10); |
Customizing Search Logic
You can customize the search logic further by overriding the search
method or adding filters based on your application needs.
Handling Typos
Laravel Scout automatically handles typos in search queries. You can tweak this behavior in the configuration settings or the underlying search driver (e.g., Algolia).
Summary
You’ve successfully added full-text search functionality to your Laravel models. Here’s a quick recap of the steps:
- Install Laravel Scout and configure it.
- Create a full-text index on the desired columns.
- Use the Searchable trait in your model.
- Index existing records for searching.
- Perform searches using the
search
method. - Create a search form and handle search requests.
- Laravel Breeze – Simple authentication starter kit
- Laravel Jetstream – Scaffolding for Laravel apps
- Laravel Passport – API authentication via OAuth2
- Laravel Sanctum – Simple API authentication
- Spatie Laravel Permission – Role and permission management
- Laravel Cashier – Subscription billing with Stripe
- Laravel Scout – Full-text search using Algolia
- Laravel Socialite – OAuth authentication (Google, Facebook, etc.)
- Laravel Excel – Excel import and export for Laravel
- Laravel Horizon – Redis queues monitoring
- Laravel Nova – Admin panel for Laravel
- Laravel Fortify – Backend authentication for Laravel
- Laravel Vapor – Serverless deployment on AWS
- Laravel Telescope – Debugging assistant for Laravel
- Laravel Dusk – Browser testing
- Laravel Mix – API for compiling assets
- Spatie Laravel Backup – Backup management
- Laravel Livewire – Building dynamic UIs
- Spatie Laravel Media Library – Manage media uploads
- Laravel Excel – Excel spreadsheet handling
- Laravel Debugbar – Debug tool for Laravel
- Laravel WebSockets – Real-time communication
- Spatie Laravel Sitemap – Generate sitemaps
- Laravel Spark – SaaS scaffolding
- Laravel Envoy – Task runner for deployment
- Spatie Laravel Translatable – Multilingual model support
- Laravel Backpack – Admin panel
- Laravel AdminLTE – Admin interface template
- Laravel Collective Forms & HTML – Simplified form and HTML generation
- Spatie Laravel Analytics – Google Analytics integration
- Laravel Eloquent Sluggable – Automatically create slugs
- Laravel Charts – Chart integration
- Laravel Auditing – Track changes in models
- Laravel JWT Auth – JSON Web Token authentication
- Laravel Queue Monitor – Monitor job queues
- Spatie Laravel Query Builder – Filter, sort, and include relationships in Eloquent queries
- Laravel Datatables – jQuery Datatables API
- Laravel Localization – Multilingual support for views and routes
- Laravel Acl Manager – Access control list manager
- Laravel Activity Log – Record activity in your app
- Laravel Roles – Role-based access control
- Spatie Laravel Tags – Tagging models
- Laravel Installer – CLI installer for Laravel
- Laravel Breadcrumbs – Generate breadcrumbs in Laravel
- Laravel Mailgun – Mailgun integration for Laravel
- Laravel Trustup Model History – Store model change history
- Laravel Deployer – Deployment automation tool
- Laravel Auth – Custom authentication guards
- Laravel CORS – Cross-Origin Resource Sharing (CORS) support
- Laravel Notifications – Send notifications through multiple channels
- Spatie Laravel Http Logger – Log HTTP requests
- Laravel Permission Manager – Manage permissions easily
- Laravel Stubs – Customize default stubs in Laravel
- Laravel Fast Excel – Speed up Excel exports
- Laravel Image – Image processing
- Spatie Laravel Backup Server – Centralize backups for Laravel apps
- Laravel Forge API – Manage servers through the Forge API
- Laravel Blade SVG – Use SVGs in Blade templates
- Laravel Ban – Ban/unban users from your application
- Laravel API Response – Standardize API responses
- Laravel SEO – Manage SEO meta tags
- Laravel Settings – Store and retrieve settings
- Laravel DOMPDF – Generate PDFs
- Laravel Turbo – Full-stack framework for building modern web apps
- Spatie Laravel Event Sourcing – Event sourcing implementation
- Laravel Jetstream Inertia – Jetstream’s Inertia.js integration
- Laravel Envoy Tasks – Task automation
- Laravel Likeable – Like/dislike functionality
- Laravel GeoIP – Determine visitor’s geographic location
- Laravel Country State City – Dropdowns for country, state, and city
- Laravel Hashids – Generate short unique hashes
- Laravel Repository – Repository pattern for Laravel
- Laravel UUID – UUID generation for models
- Spatie Laravel Medialibrary Pro – Enhanced media management
- Laravel Queue Monitor – Monitor Laravel job queues
- Laravel User Activity – Monitor user activity
- Laravel DB Snapshots – Create database snapshots
- Laravel Twilio – Twilio integration
- Laravel Roles – Role-based permission handling
- Laravel Translatable – Add translations to Eloquent models
- Laravel Teamwork – Manage teams in multi-tenant apps
- Laravel Full Text Search – Add full-text search to Laravel models
- Laravel File Manager – File and media management
- Laravel User Timezones – Automatically detect user time zones
- Laravel ChartsJS – Render charts with ChartsJS
- Laravel Stripe – Stripe API integration
- Laravel PDF Generator – PDF generation
- Laravel Elasticsearch – Elasticsearch integration
- Laravel Simple Qrcode – Generate QR codes
- Laravel Timezone – Manage timezones and conversions
- Laravel Collective API – API management for Laravel
- Laravel Rest API Boilerplate – REST API starter kit
- Laravel Multi Auth – Multi-authentication functionality
- Laravel Voyager – Admin panel for Laravel
- Laravel Voyager Database – Database manager for Voyager
- Laravel Categories – Handle categories for models
- Laravel Multitenancy – Multi-tenancy implementation
- Laravel Access Control – Advanced access control for users
- Laravel Menus – Menu management
- Laravel Translatable Routes – Multilingual route handling