DEV Community 👩‍💻👨‍💻

Nasrul Hazim Bin Mohamad
Nasrul Hazim Bin Mohamad

Posted on

Laravel Scout: Create A Global Search

This is continuity form the previous post here.

I was asked if it is possible, if we create a Global Search? Yes it is possible. We are the programmer, we program things how they should behave and act.

I did minor changes on route and helper, then it's done!

TLDR;

The route:

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::middleware('auth:sanctum')->get('/search', function (Request $request) {
    abort_if(
        empty($request->search),
        404,
        'Please provide search keyword'
    );

    return search($request);
});
Enter fullscreen mode Exit fullscreen mode

And the helper:

<?php

use App\Enums\SearchType;
use Illuminate\Http\Request;
use Laravel\Scout\Searchable;

if (! function_exists('search')) {
    function search(Request $request = null)
    {
        if(is_null($request)) {
            $request = request();
        }

        $type = SearchType::tryFrom($request->type);
        $keyword = $request->search;
        $paginate = $request->query('paginate', false);
        $types = empty($type) ? SearchType::cases() : [$type];

        $data = [];
        foreach ($types as $type) {
            throw_if(
                ! in_array(Searchable::class, class_uses_recursive($type->value))
            );

            $class = $type->value;

            $query = $class::search($keyword);

            $data[$type->label] = $paginate
                ? $query->paginate()
                : $query->first();
        }

        return [
            'data' => $data,
            'meta' => [
                'searched_at' => date('Y-m-d H:i:s')
            ],
        ];
    }
}
Enter fullscreen mode Exit fullscreen mode

I also update my enum, remove the labels() ovewrite:

<?php

namespace App\Enums;

use Spatie\Enum\Laravel\Enum;

/**
 * @method static self user()
 * @method static self profile()
 */
class SearchType extends Enum
{
    public static function values(): array
    {
        return [
            'user' => \App\Models\User::class,
            'profile' => \Profile\Models\Profile::class,
        ];
    }
}
Enter fullscreen mode Exit fullscreen mode

Now you are done! A Global Search in action.

Top comments (0)

Update Your DEV Experience Level:

Settings

Go to your customization settings to nudge your home feed to show content more relevant to your developer experience level. 🛠