DeveloperBreeze

Search Filters Development Tutorials, Guides & Insights

Unlock 1+ expert-curated search filters tutorials, real-world code snippets, and modern dev strategies. From fundamentals to advanced topics, boost your search filters skills on DeveloperBreeze.

Implementing Full-Text Search in Laravel

Tutorial November 16, 2024
php

    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,
            ]);
        }
    }

In routes/web.php, define routes for search: