Search one column from a Vue field

when() adds a like query only when the search box is not empty. Bind the word. Do not paste it into SQL.

For your AI agent

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

Read https://laravel-vuejs.space/laravel-where-search-vue.md
when() adds a like query only when the search box is not empty. Bind the word. Do not paste it into SQL.
Do not paste it into SQL.
Do not use whereRaw with the request pasted in.
Do not LIKE against every column "to be helpful" unless you indexed that search on purpose.
Show the diff. Do not commit.
On this page · 3 sections
  1. The fix
  2. What to avoid
  3. FAQ

People searching “Laravel Vue search” interpolate the query string into SQL. The CRUD guide already has the filter form. This page is the query.

TL;DR

  • when() adds a like query only when the search box is not empty.
  • Bind the word.
  • Do not paste it into SQL.
  • Do not use whereRaw with the request pasted in.

Who it's for: Laravel + Vue developers on Inertia

Applies to: Laravel 13 · Inertia 3 · Vue 3

The fix#

php
$search = $request->string('search')->trim()->toString();

$posts = Post::query()
    ->when($search !== '', function ($query) use ($search) {
        $query->where('title', 'like', '%'.$search.'%');
    })
    ->orderBy('id')
    ->paginate(12)
    ->withQueryString();

where() binds the value. The percent signs are wildcards around a bound string, not a second query language. withQueryString() keeps ?search= on the pagination links.

The Vue field is named search. Empty string skips the clause, so the first visit is the full list.

What to avoid#

Gotcha

Do not use whereRaw with the request pasted in. Do not LIKE against every column “to be helpful” unless you indexed that search on purpose. A leading wildcard does not use a normal index. That is acceptable on a small table and a problem on a large one.

FAQ#

How do I search one column from a Vue field?

when() adds a like query only when the search box is not empty. Bind the word. Do not paste it into SQL.

What goes wrong with Laravel Vue search?

Many developers interpolate the query string into SQL. Do not use whereRaw with the request pasted in.

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.