Laravel offers powerful full-text search capabilities via the whereFullText
and orWhereFullText
methods, providing a more refined approach to data retrieval than simple LIKE
statements.
The whereFullText
methods seamlessly integrate with your database's built-in full-text search functionality. A basic example follows:
use Illuminate\Support\Facades\DB; $users = DB::table('users') ->whereFullText('bio', 'web developer') ->get();
This can be expanded to create robust search features for applications like blogs or content management systems. The following illustrates a search across multiple columns with category filtering:
// ArticleController.php public function search(Request $request) { return Article::query() ->whereFullText(['title', 'content'], $request->search) ->when($request->category, function ($query, $category) { $query->where('category', $category); }) ->orderBy('published_at', 'desc') ->paginate(15); } // migration Schema::create('articles', function (Blueprint $table) { $table->id(); $table->string('title'); $table->text('content'); $table->string('category'); $table->timestamp('published_at'); $table->fullText(['title', 'content']); });
Laravel automatically generates the correct SQL for your database. For MariaDB and MySQL, it defaults to MATCH AGAINST
statements using natural language mode.
This approach streamlines complex search logic while maintaining efficient query speeds for moderately sized projects. However, for applications demanding advanced search or handling substantial datasets, dedicated search engines such as ElasticSearch or Meilisearch are recommended.
The above is the detailed content of Harnessing Full-Text Search in Laravel. For more information, please follow other related articles on the PHP Chinese website!