Skip to main content Skip to navigation

Guides: SearchConstructor

The SearchConstructor is one of the Constructor Classes of Hiker. It's used to create the search part of the Chrome.

Here's an example of how it's used:

<?php

namespace App\Hiker\Chrome;

use Hiker\Components\Search\SearchConstructor;


class Search extends SearchConstructor
{
    protected function contexts(): array
    {
        return [
            SearchContext::make('*', 'Tout')
                ->keystrokes(['meta', 'shift', 'p'])
                ->default()
                ->resources([
                    Cats::class,
                    Dogs::class,
                ]),

            SearchContext::make('Cats', 'Chats')
                ->keystrokes(['meta', 'shift', 'o'])
                ->resources([Cats::class]),

            SearchContext::make('Dogs', 'Chiens')
                ->keystrokes(['meta', 'shift', 'u'])
                ->resources([Dogs::class]),
        ];
    }

    public function recent(): array
    {
        $cacheKey = auth()->user()->id.'_search';

        if ($searches = cache($cacheKey)) {
            $searches = array_reverse(json_decode($searches));
        } else {
            $searches = [];
        }

        return array_map(function ($search) {
            return SearchItem::make($search->raw, $search->context);
        }, $searches);
    }
}

Required methods

contexts(): array

Description:

Get the list of available search contexts

Example:

protected function contexts(): array
{
    return [
        SearchContext::make('*', 'Tout')
            ->keystrokes(['meta', 'shift', 'p'])
            ->default()
            ->resources([
                Cats::class,
                Dogs::class,
            ]),

        SearchContext::make('Cats', 'Chats')
            ->keystrokes(['meta', 'shift', 'o'])
            ->resources([Cats::class]),

        SearchContext::make('Dogs', 'Chiens')
            ->keystrokes(['meta', 'shift', 'u'])
            ->resources([Dogs::class]),
    ];
}

recent(): array

Description:

Get the list of recent searches

Example:

public function recent(): array
{
    $cacheKey = auth()->user()->id.'_search';

    if ($searches = cache($cacheKey)) {
        $searches = array_reverse(json_decode($searches));
    } else {
        $searches = [];
    }

    return array_map(function ($search) {
        return SearchItem::make($search->raw, $search->context);
        }, $searches);
    }
}

Optional methods