简体   繁体   中英

Laravel search column starts with the given word

I got a problem when search query using Laravel where and like.

$words = 'pa';

$query = Category::where(function ($query) use ($words) {
                $query->where('name', 'like', '%'.$words)
                      ->orWhere('name', 'like', $words . '%')
                })->pluck('name');

The result is:

[{Chocolate Spa, Zen Spa, Disco Party}]

The expected result is only Party .

I want it search name column starts with the given word not contain that words.

How can I achieve that search method?

This should work:

$query = Category::where('name', 'like', $words.'%')
    ->orWhere('name', 'like', '% '.$words.'%'))
    ->pluck('name');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM