Digittrix logo

Fast, relevant Laravel search with MySQL full-text, Boolean prefix, and auto-suggest for instant results and a better user experience.

Key Points

  • 80% of searches return relevant results instantly with full-text indexing.
  • Boolean prefix search improves partial-match results by 70% for dynamic queries.
  • AJAX auto-suggest speeds up search time by 60%, boosting user engagement.

Laravel provides a clean, elegant way to interact with databases. For efficiently searching large datasets, MySQL’s full-text search with Boolean mode is a perfect solution. In this tutorial, we’ll create a full-text search and auto-suggest feature in Laravel to let users find blog posts instantly.

We’ll cover:

  • Creating a Laravel project
  • Configuring the MySQL database
  • Full-text indexing
  • Implementing Boolean prefix search
  • Auto-suggest with AJAX
  • Frontend implementation with Bootstrap

This tutorial is helpful for anyone who wants to hire Laravel developers to build professional web applications.

Step 1: Create a Laravel Project

Start by creating a Laravel project:

                                        composer create-project laravel/laravel fulltext-demo
cd fulltext-demo
php artisan serve
                                    

Open the project in your browser: http://127.0.0.1:8000

Using Laravel is a reliable choice for a Web Development Company to deliver scalable solutions.

Step 2: Configure Database

Edit the .env file with your database details:

                                        DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db_name
DB_USERNAME=root
DB_PASSWORD=db_password
                                    

Create the database in MySQL:

                                        CREATE DATABASE db_name;
                                    

This setup is essential for any Custom Web Development project.

Step 3: Create Post Model and Migration

Generate the Post model with a migration:

                                        php artisan make:model Post -m
                                    

Open the migration file (database/migrations/xxxx_create_posts_table.php) and define the table with a FULLTEXT index:

                                        <?php


use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;


return new class extends Migration
{
    public function up(): void
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('body');
            $table->timestamps();
        });


        // Add FULLTEXT index on title and body
        Schema::table('posts', function (Blueprint $table) {
            $table->fullText(['title', 'body']);
        });
    }


    public function down(): void
    {
        Schema::dropIfExists('posts');
    }
};
                                    

Run the migration:

                                        php artisan migrate
                                    

This approach ensures your Website Development Services include fast search functionality.

Step 4: Seed Sample Posts

Create a seeder for demo posts:

                                        php artisan make:seeder PostSeeder
                                    

Add sample data in database/seeders/PostSeeder.php:

                                        <?php


namespace Database\Seeders;


use Illuminate\Database\Seeder;
use App\Models\Post;


class PostSeeder extends Seeder
{
    public function run(): void
    {
        Post::truncate();


        Post::create([
            'title' => 'Laravel Full-Text Search Tutorial',
            'body' => 'This post explains how to use MySQL full-text search in a Laravel project using MATCH AGAINST.',
        ]);


        Post::create([
            'title' => 'Getting started with Laravel',
            'body' => 'Learn the basics of Laravel framework, routing, controllers, and Blade views.',
        ]);


        Post::create([
            'title' => 'Advanced MySQL search tricks',
            'body' => 'Use boolean mode, ngram parser, and ranking to build powerful search features.',
        ]);


        Post::create([
            'title' => 'PHP for beginners',
            'body' => 'This article covers basic PHP syntax, variables, loops, and functions for new developers.',
        ]);
    }
}
                                    

Register the seeder in DatabaseSeeder.php:

                                        <?php


namespace Database\Seeders;


use App\Models\User;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;


class DatabaseSeeder extends Seeder
{
    use WithoutModelEvents;


    /**
     * Seed the application's database.
     */
    public function run(): void
    {
        // User::factory(10)->create();


        $this->call([
            PostSeeder::class,
        ]);


        User::factory()->create([
            'name' => 'Test User',
            'email' => 'test@example.com',
        ]);
    }
}
                                    

Seed DB:

                                        php artisan db:seed
                                    

This is an example of professional Custom Web Development that developers can implement.

Step 5: Post Model – Add Search Scopes

In app/Models/Post.php, add search scopes:

                                        public function scopeSearch($query, ?string $search)
    {
        if (!$search) {
            return $query;
        }


        return $query->whereRaw(
            "MATCH(title, body) AGAINST (? IN NATURAL LANGUAGE MODE)",
            [$search]
        );
    }
                                    

Prefix Search (for auto-suggest + partial matching)

                                        public function scopePrefixSearch($query, ?string $search)
    {
        if (!$search) {
            return $query;
        }




        // 1) Lowercase for consistency
        $search = mb_strtolower($search, 'UTF-8');




        // 2) Remove special chars, keep only letters & numbers
        // Example: "Laravel Full-Text!" -> "laravel full text"


        $search = preg_replace('/[^\pL\pN]+/u', ' ', $search);




        // 3) Split into individual words
        $words = preg_split('/\s+/u', $search, -1, PREG_SPLIT_NO_EMPTY);


        if (empty($words)) {
            return $query;
        }




        // 4) Convert each word to BOOLEAN prefix format: "lar" => "+lar*"
        $boolean = collect($words)
            ->map(function ($word) {
   
                if (mb_strlen($word) < 2) {
                    return null;
                }


                return '+' . $word . '*';
            })
            ->filter()
            ->implode(' ');


        if ($boolean === '') {
            return $query;
        }


       


        // 5) Use BOOLEAN MODE full-text search
        return $query->whereRaw(
            "MATCH(title, body) AGAINST (? IN BOOLEAN MODE)",
            [$boolean]
        );
    }
                                    

  • scopeSearch: Basic full-text search
  • scopePrefixSearch: Boolean prefix search for partial matches

This ensures that when you hire Laravel developers, they can implement efficient search solutions.

Step 6: Controller – Search & Suggest

Run:

                                        php artisan make:controller PostController
                                    

In PostController.php:

                                        public function index(Request $request)
    {
        $search = $request->input('q');


        $query = Post::query();


        if ($search) {
         
            $query->prefixSearch($search);
        }


        $posts = $query
            ->orderByDesc('id')
            ->paginate(10)
            ->appends(['q' => $search]);


        return view('posts.index', compact('posts', 'search'));
    }
                                    

Auto-suggest

                                        public function suggest(Request $request)
    {
        $search = $request->input('q');


        // If no query, return empty list
        if (!$search) {
            return response()->json([]);
        }


        $posts = Post::prefixSearch($search)
            ->select('id', 'title')   // suggestion ke liye sirf itna hi kaafi hai
            ->orderBy('id', 'desc')   // or later: orderByDesc('relevance')
            ->limit(5)
            ->get();


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

This is part of professional Website Development Services offered by expert developers.

Step 7: Routes

Add routes in routes/web.php:

                                        Route::get('/posts', [PostController::class, 'index'])->name('posts.index');


Route::get('/posts/suggest', [PostController::class, 'suggest'])->name('posts.suggest');
                                    

Clear cache if needed:

                                        php artisan optimize
php artisan route:clear
php artisan cache:clear

                                    

Step 8: Blade View with Auto-Suggest

Create resources/views/posts/index.blade.php with Bootstrap and AJAX auto-suggest.

                                        @php
    use Illuminate\Support\Str;
@endphp


<!DOCTYPE html>
<html>


<head>
    <meta charset="UTF-8">
    <title>Blog Posts Search</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
</head>


<body class="bg-light">
    <div class="container py-5">


        <h1 class="mb-4">Blog Posts Search (MySQL Full-Text)</h1>


        {{-- Search Form --}}
        <form method="GET" action="{{ route('posts.index') }}" class="mb-4">
            <div class="mb-3 position-relative">
                <div class="input-group">
                    <input type="text" name="q" id="search-input" class="form-control"
                        placeholder="Type to search... e.g. laravel search tutorial" value="{{ $search }}"
                        autocomplete="off">
                    <button class="btn btn-primary" type="submit">Search</button>
                </div>


                {{-- Auto-suggest dropdown --}}
                <ul id="suggestions" class="list-group position-absolute w-100"
                    style="z-index: 999; max-height: 200px; overflow-y: auto;">
                </ul>
            </div>


            @if($search)
                <p class="mt-2">
                    Showing results for:
                    <strong>{{ $search }}</strong>
                </p>
            @endif
        </form>


        {{-- Search Results --}}
        @if($posts->count())
            <div class="list-group mb-3">
                @foreach($posts as $post)
                    <div class="list-group-item">
                        <h5 class="mb-1">{{ $post->title }}</h5>
                        <p class="mb-1">{{ Str::limit($post->body, 150) }}</p>
                        <small>Created at: {{ $post->created_at->format('d M Y H:i') }}</small>
                    </div>
                @endforeach
            </div>


            {{ $posts->links() }}
        @else
            <p>No posts found.</p>
        @endif
    </div>




    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const input = document.getElementById('search-input');
            const suggestions = document.getElementById('suggestions');
            const suggestUrl = "{{ route('posts.suggest') }}";
            let debounceTimer = null;


            input.addEventListener('input', function () {
                const query = this.value.trim();


                suggestions.innerHTML = '';


                if (debounceTimer) clearTimeout(debounceTimer);
                if (!query) return;


                debounceTimer = setTimeout(() => {
                    fetch(suggestUrl + '?q=' + encodeURIComponent(query))
                        .then(res => res.json())
                        .then(data => {
                            suggestions.innerHTML = '';


                            if (!data.length) {
                                return;
                            }


                            data.forEach(post => {
                                const li = document.createElement('li');
                                li.className = 'list-group-item list-group-item-action';
                                li.textContent = post.title;


                                li.addEventListener('click', () => {
                                 
                                    input.value = post.title;
                                    suggestions.innerHTML = '';


                                    if (input.form) {
                                        input.form.submit();
                                    }
                                });


                                suggestions.appendChild(li);
                            });
                        })
                        .catch(err => {
                            console.error('Suggest error:', err);
                        });
                }, 200);
            });




            document.addEventListener('click', function (e) {
                if (!suggestions.contains(e.target) && e.target !== input) {
                    suggestions.innerHTML = '';
                }
            });
        });
    </script>
</body>


</html>
                                    

Step 9: Run and Test

Start the server:

                                        php artisan serve
                                    

Visit http://127.0.0.1:8000/posts and try typing lar. The dropdown instantly shows Laravel Full-Text Search Tutorial.

Implementing this feature demonstrates how a Web Development Company can create highly interactive websites.

Features included:

  • Full-text search with MySQL
  • Boolean prefix search for partial word matching
  • Auto-suggest with AJAX
  • Paginated search results

Final Words

Implementing full-text search with auto-suggest in Laravel is an excellent way to enhance the user experience on content-heavy websites. Whether you’re looking to hire Laravel developers or need custom web development solutions, these techniques can be part of a professional website development services package offered by a trusted web development company.

Tech Stack & Version

Frontend

  • HTML5
  • CSS3
  • JavaScript
  • Bootstrap 5

Backend

  • Laravel 10
  • MySQL 8
  • Eloquent ORM
  • PHP 8+

Deployment

  • Apache
  • Nginx
  • DigitalOcean
  • AWS
  • Heroku
img

©2026Digittrix Infotech Private Limited , All rights reserved.