Laravel Scout database engine: full-text search for a Vue page, no Meilisearch

Add search to a Laravel + Vue app with Scout's database engine: LIKE, prefix and Postgres full-text columns, relevance ranking and an Inertia search page. 10 tests on PostgreSQL 18.

For your AI agent

Copies a prompt. Paste it into the AI agent you already have open.

Read https://laravel-vuejs.space/laravel-scout-database-engine-vue.md
Add search to a Laravel + Vue app with Scout's database engine: LIKE, prefix and Postgres full-text columns, relevance ranking and an Inertia search page. 10 tests on PostgreSQL 18.
Show the diff. Do not commit.
On this page · 10 sections
  1. When the database engine is enough
  2. Set it up
  3. What Scout actually runs
  4. Relevance and websearch mode (Postgres)
  5. Filters and pagination
  6. The Vue search page
  7. Gotchas we hit
  8. Recap
  9. FAQ
  10. Next steps
  11. Sources

Your users want a search box. The usual advice is to run Meilisearch or pay for Algolia, then keep an index in sync with a queue worker. For a blog, a docs site or an admin panel with a few hundred thousand rows, that’s a lot of moving parts. Laravel Scout ships a database engine that searches the tables you already have, with real full-text indexes on MySQL and PostgreSQL.

TL;DR

  • composer require laravel/scout, set SCOUT_DRIVER=database, add Searchable to the model. There’s no index to build or sync: new rows are searchable right away.
  • By default, every column in toSearchableArray() gets a %term% LIKE (ilike on Postgres). Mark columns with #[SearchUsingPrefix] or #[SearchUsingFullText] to make them faster and smarter.
  • Full-text columns need a fullText index. On Postgres, Scout then ranks results with ts_rank and can use websearch mode for quotes and -exclusions.
  • Article::search($q)->where('status', 'published')->paginate(15) returns a normal paginator you can pass straight to an Inertia page.

What you'll learn

  • Turning on the Scout database engine
  • Choosing LIKE, prefix or full-text per column with PHP attributes
  • Postgres full-text options: language, websearch mode and relevance order
  • A debounced Inertia + Vue search page with pagination

Who it's for: Laravel + Vue developers who need search on MySQL or PostgreSQL and don't want a search server yet

Tested with: Laravel 13.40 · laravel/scout 11.9.0 · PostgreSQL 18.6 · PHP 8.4 · Pest 4 (10 tests, 21 assertions)

When the database engine is enough#

You needDatabase engineMeilisearch / Algolia / Typesense
Search titles, slugs and bodies of your own rowsYesYes
Stemming (“workers” finds “worker”)Yes, on full-text columnsYes
Typo tolerance (“larvel”)NoYes
Facets, geo search, synonymsNoYes
Extra infrastructure and a sync queueNoneA server or SaaS, plus queued indexing

The Scout docs put it this way: the database engine is “all you need” for most applications, and it currently supports MySQL and PostgreSQL. The database engine has existed since Scout 9.4 (PR #564, January 2022). We tested it on Scout 11.9.0.

Set it up#

bash
composer require laravel/scout
php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"
.envini
SCOUT_DRIVER=database
app/Models/Article.phpphp
use Laravel\Scout\Attributes\SearchUsingFullText;
use Laravel\Scout\Attributes\SearchUsingPrefix;
use Laravel\Scout\Searchable;

class Article extends Model
{
    use Searchable;

    #[SearchUsingPrefix(['id', 'slug'])]
    #[SearchUsingFullText(['body'], ['mode' => 'websearch', 'language' => 'english'])]
    public function toSearchableArray(): array
    {
        return [
            'id' => $this->id,
            'title' => $this->title,   // no attribute: %LIKE%
            'slug' => $this->slug,     // prefix: LIKE 'term%'
            'body' => $this->body,     // full-text index
        ];
    }
}

The array returned by toSearchableArray() isn’t stored anywhere with this engine. Scout only uses its keys as the list of columns to search, so every key must be a real column on the table.

A full-text column needs a full-text index:

database/migrations/xxxx_add_fulltext_to_articles.phpphp
Schema::table('articles', function (Blueprint $table) {
    $table->fullText('body');
});

On PostgreSQL, Laravel creates a GIN index on to_tsvector('english', body). We checked with EXPLAIN that Postgres uses it (Bitmap Index Scan on articles_body_fulltext) for the exact expression Scout generates.

What Scout actually runs#

This is the SQL our lab logged for Article::search('LARAVEL') with the model above:

sql
select * from "articles" where (
  "articles"."id"::text ilike ?          -- 'LARAVEL%'
  or "articles"."title"::text ilike ?    -- '%LARAVEL%'
  or "articles"."slug"::text ilike ?     -- 'LARAVEL%'
  or (to_tsvector('english', "articles"."body")) @@ websearch_to_tsquery('english', ?)
) order by ts_rank(to_tsvector('english', articles.body), websearch_to_tsquery(?)) desc

What that means in practice:

  • LIKE columns match anywhere in the value. On Postgres, Scout uses ilike, so LARAVEL found “Deploy Laravel…”. A leading % can’t use a normal B-tree index, so keep plain LIKE for short columns like titles.
  • Prefix columns only match the start (laravel-q%). That’s right for slugs, SKUs and emails, and it can use an index.
  • Full-text columns stem words. restart workers found the article whose body says “workers restart after the release”. The same query with plain LIKE found nothing, because %restart workers% isn’t a substring of the body.
  • A numeric query also matches the primary key, so searching 3 returns article 3. Leave id out of the array if you don’t want that.

Relevance and websearch mode (Postgres)#

On PostgreSQL with at least one full-text column and no orderBy() of your own, Scout orders by ts_rank, so the best match comes first. With 'mode' => 'websearch', users can type "exact phrase" or deploy -symlink. In our lab, deploy -symlink returned the article that mentions deploying a form request and excluded the zero-downtime deploy article (its body mentions the symlink).

Gotcha: websearch reads a leading minus as NOT

In websearch mode, a query that starts with - means “everything without this word”. A user typing -reactivity gets almost the whole table back. If your search box can receive slugs or SKUs that start with a dash, use the default plainto_tsquery mode or trim the input.

MySQL orders full-text matches by relevance on its own. Scout only adds the ts_rank order on Postgres.

Filters and pagination#

app/Http/Controllers/ArticleSearchController.phpphp
use Inertia\Inertia;

public function __invoke(Request $request)
{
    $q = (string) $request->string('q')->trim();

    return Inertia::render('Articles/Search', [
        'q' => $q,
        'results' => $q === ''
            ? null
            : Article::search($q)
                ->where('status', 'published')                          // a plain where on the table
                ->query(fn ($query) => $query->select('id', 'title', 'slug')->with('author:id,name'))
                ->paginate(15)
                ->withQueryString(),
    ]);
}
  • where(), whereIn() and whereNotIn() become normal SQL constraints. Our draft article never showed up once we added where('status', 'published').
  • query() lets you change the Eloquent query (select fewer columns, eager load relations). We checked that the select reaches the SQL.
  • paginate() returns a LengthAwarePaginator, just like Eloquent’s. withQueryString() keeps ?q= on the page links.

The Vue search page#

resources/js/pages/Articles/Search.vuevue
<script setup lang="ts">
import { ref, watch } from 'vue'
import { router, Link } from '@inertiajs/vue3'
import { useDebounceFn } from '@vueuse/core'

const props = defineProps<{
  q: string
  results: { data: { id: number; title: string; slug: string }[]; links: { url: string | null; label: string; active: boolean }[] } | null
}>()

const q = ref(props.q)

const search = useDebounceFn(() => {
  router.get('/search', { q: q.value }, { preserveState: true, replace: true, only: ['q', 'results'] })
}, 300)

watch(q, search)
</script>

<template>
  <input v-model="q" type="search" placeholder="Search articles" aria-label="Search articles" />

  <p v-if="results && results.data.length === 0">No articles match “{{ q }}”.</p>

  <ul v-if="results">
    <li v-for="a in results.data" :key="a.id"><Link :href="`/${a.slug}`">{{ a.title }}</Link></li>
  </ul>
</template>
  • replace: true stops every keystroke from adding a history entry.
  • only: ['q', 'results'] makes it a partial reload, so shared props and the layout aren’t recomputed.
  • The 300 ms debounce keeps you from running a query per letter. If you also want to cancel requests already in flight, see onWatcherCleanup.

Try it yourself

On a MySQL or Postgres app: composer require laravel/scout, set SCOUT_DRIVER=database, add Searchable and a toSearchableArray() with one #[SearchUsingFullText] column and its fullText index. Then run php artisan tinker and try App\Models\Article::search('your words')->get(). No import step is needed.

Gotchas we hit#

  • Every key is a column. A computed key such as 'author_name' => $this->author->name breaks the query, because Scout writes where "author_name" ilike …. Put related data in a real column, or switch to a search server.
  • searchableAs() and getScoutKey() do nothing with the database engine. It always searches the model’s own table by primary key.
  • No full-text index, slow search. #[SearchUsingFullText] on a column without a fullText index still runs, but as a full table scan.
  • scout:import isn’t needed. There’s no external index. Queued indexing ('queue' => true) also doesn’t matter for this engine.
  • SQLite and SQL Server aren’t supported by the database engine. For tests on SQLite, the collection driver works, but it loads every row into PHP, so keep it out of production.

Recap#

  • SCOUT_DRIVER=database gives you search with no extra service and no indexing step.
  • Plain columns use %LIKE% (ilike on Postgres), #[SearchUsingPrefix] uses term%, and #[SearchUsingFullText] uses the full-text index with stemming.
  • On Postgres, full-text results are ranked with ts_rank, and websearch mode supports quotes and -exclusions.
  • search()->where()->query()->paginate() drops straight into an Inertia page, and a debounced router.get with replace and only keeps the Vue side smooth.
  • Move to Meilisearch or Typesense when you need typo tolerance, facets or synonyms. The model code barely changes.

FAQ#

Does the Scout database engine need Meilisearch or Algolia?

No. It queries your own MySQL or PostgreSQL tables directly. There is no index to import or keep in sync.

Which databases does the Scout database engine support?

MySQL and PostgreSQL, according to the Scout docs. For SQLite tests, use the collection driver, which filters in PHP and is only meant for small data.

How do I make Scout use a full-text index?

Add a fullText index in a migration, then put #[SearchUsingFullText(['body'])] on toSearchableArray(). Other columns keep using LIKE unless you mark them as prefix columns.

Can the database engine rank results by relevance?

On PostgreSQL, yes: with a full-text column and no orderBy(), Scout orders by ts_rank. MySQL full-text matching already orders by relevance.

Does Scout’s database engine handle typos?

No. Full-text search stems words but doesn’t fix misspellings. If typo tolerance matters, switch the driver to Meilisearch or Typesense.

Next steps#

Sources#

Found this useful?

Ask questions, share what you built.

Join thousands of Laravel and Vue developers in our Facebook group, or get new posts in your Telegram feed. Sharing this article helps too.

Keep reading

Newsletter

Get the best of Laravel & Vue, once a month.

One short email with new guides, release notes worth reading and hand-picked community links. No spam, unsubscribe any time.