Full-text search allows users to efficiently search through large amounts of text data in your application. Laravel supports basic query-based searches, but for advanced search functionality, integrating full-text search techniques can significantly enhance user experience. This tutorial will guide you through implementing full-text search using MySQL.
Scenario: Full-Text Search in Laravel
Consider an application where:
- Users need to search through posts, articles, or product descriptions.
- Basic SQL queries (
likeclauses) are too slow or inefficient for large datasets. - You want features like relevance ranking, partial matches, and advanced filtering.
We’ll implement full-text search using MySQL’s built-in capabilities.
Step 1: Setting Up the Laravel Application
- Install Laravel:
Create a new Laravel project using Composer:
composer create-project --prefer-dist laravel/laravel laravel-fulltext-app
cd laravel-fulltext-app
- Set Up the Database:
Update the .env file with your database connection details:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_fulltext
DB_USERNAME=root
DB_PASSWORD=
- Run Database Migrations:
Generate the database schema with Laravel migrations:
php artisan migrate
Step 2: Creating the Post Model and Migration
- Generate the Post Model and Migration:
Run the following command to create the Post model and migration file:
php artisan make:model Post -m
- Define the
postsTable Schema:
Open the migration file in database/migrations/xxxx_xx_xx_create_posts_table.php and update it as follows:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostsTable extends Migration
{
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('content');
$table->timestamps();
$table->fullText(['title', 'content']); // Add a full-text index
});
}
public function down()
{
Schema::dropIfExists('posts');
}
}
- Run the Migration:
Apply the migration to create the posts table:
php artisan migrate
Step 3: Define the Post Model
- Update the
PostModel:
Open the app/Models/Post.php file and define the model:
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
protected $fillable = ['title', 'content'];
}
- Seed the Database with Test Data:
Use a factory to generate sample posts:
php artisan make:factory PostFactory --model=Post
Open database/factories/PostFactory.php and define the factory:
namespace Database\Factories;
use App\Models\Post;
use Illuminate\Database\Eloquent\Factories\Factory;
class PostFactory extends Factory
{
protected $model = Post::class;
public function definition()
{
return [
'title' => $this->faker->sentence,
'content' => $this->faker->paragraphs(3, true),
];
}
}
Seed the database with sample posts:
php artisan tinker
use App\Models\Post;
Post::factory()->count(50)->create();
Step 4: Implementing Full-Text Search in MySQL
- Perform a Full-Text Search Query:
Use Laravel’s query builder to perform a full-text search:
$results = DB::table('posts')
->whereRaw("MATCH(title, content) AGAINST(?)", ['search term'])
->get();
- SearchController:
Create a SearchController:
php artisan make:controller SearchController
In app/Http/Controllers/SearchController.php, define the index and search methods:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class SearchController extends Controller
{
public function search(Request $request)
{
$query = $request->input('query');
if (empty($query) || strlen($query) < 4) {
return redirect()->route('search.index')->withErrors('Search term must be at least 4 characters long.');
}
// Perform full-text search with MATCH...AGAINST
$posts = DB::table('posts')
->select('id', 'title', 'content')
->whereRaw("MATCH(title, content) AGAINST(? IN BOOLEAN MODE)", ['"' . $query . '"'])
->get();
return view('search.index', [
'posts' => $posts,
'query' => $query,
]);
}
}
- Add Routes:
In routes/web.php, define routes for search:
use App\Http\Controllers\SearchController;
Route::get('/search', [SearchController::class, 'index'])->name('search.index');
Route::get('/search/results', [SearchController::class, 'search'])->name('search.results');
Step 5: Create Layout and Views
- Create a Layout File:
Create a reusable layout file in resources/views/layouts/app.blade.php:
@yield('title', 'Laravel Full-Text Search')
@yield('content')
- Create Search Index View:
In resources/views/search/index.blade.php:
@extends('layouts.app')
@section('title', 'Search Posts')
@section('content')
Search Posts
@if(isset($posts))
Results for "{{ $query }}"
@forelse($posts as $post)
@empty
No results found for your query.
@endforelse
@endif
@endsection
- Create Single Post View:
In resources/views/posts/show.blade.php:
@extends('layouts.app')
@section('title', $post->title)
@section('content')
{{ $post->title }}
{{ $post->content }}
Back to Search
@endsection
Conclusion
In this tutorial, we explored how to implement full-text search in a Laravel application, enabling efficient and scalable search functionality for large datasets. Starting from setting up a fresh Laravel project, we defined a Post model, created migrations to structure the database, and used Laravel factories to seed sample data for testing.
We leveraged MySQL’s MATCH...AGAINST for basic full-text search, allowing us to search across multiple columns and retrieve relevant results. The tutorial also showcased how to rank results by relevance, improving the search experience for users. Additionally, we built a clean and reusable layout for the application, designed simple CSS to replace external frameworks, and created dynamic views for the search index, results, and individual post details.
Key Takeaways
- Efficient Search: MySQL’s full-text search provides a quick and reliable way to implement advanced search functionality directly in the database.
- Clean Architecture: We demonstrated how to use Laravel's MVC structure effectively, keeping logic, views, and routes organized.
- Scalable Solution: The tutorial lays the groundwork for adding more advanced features like filters, fuzzy search, or external integrations like Elasticsearch.
This tutorial equips you with a strong foundation to integrate full-text search into any Laravel project. You can now extend this implementation further by adding advanced features, such as filtering by categories or using third-party search services for even more robust functionality.
By combining Laravel’s simplicity with MySQL’s full-text capabilities, your application is now prepared to handle efficient, user-friendly search experiences that can scale with your growing dataset.