ssuhat
ssuhat

Reputation: 7656

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?

Upvotes: 3

Views: 2757

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163748

This should work:

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

Upvotes: 6

Related Questions