Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

AbehoM's avatar

Create a search with categories

What is the best way to create a search with categories like this:

The different is that I want to search for users, each user has it's own city, I wanted the categories to be the cities and the users for each city, for example, if there's 3 John I wanted to show each one in its own city.

0 likes
3 replies
AbehoM's avatar

Can anyone help me with that?

Sergiu17's avatar
Sergiu17
Best Answer
Level 60
// route where you'll send the request for search
Route::get('/users/search', 'UsersSearchController@index');

// localhost:8080/users/search?q=John
public function index(Request $request) {
    $q = $request->input('q');

    $categories = App\Category::whereHas('users', function ($query) {
        $query->where('username', 'like',  $q . '%');
    })->get();

    return $categories;
}

And probably request to search endpoint is done via AJAX,

// here's a little bit of Vue
<select>
    <optgroup v-for="category in categories" :label="category.name">
        <option v-for="user in category.users">{{ user.name }}</option>
    </optgroup>
</select>

this is very basic example, hope it helps

Please or to participate in this conversation.