Laravel Scout: Create A Global Search - TechvBlogs

Laravel Scout: Create A Global Search

Explore seamless global search with Laravel Scout for unparalleled results. Discover the world at your fingertips.


Smit Pipaliya - Author - TechvBlogs
Smit Pipaliya
 

2 months ago

TechvBlogs - Google News

Creating a Global Search in Laravel is a powerful and practical feature, and you've demonstrated a concise and effective implementation. Here's a brief breakdown of the changes you made:

Route Modification:

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);
});

In this route modification, you've added a /search endpoint that expects a search keyword. If the keyword is missing, it returns a 404 response with a relevant message. Otherwise, it calls the search() helper function.

Helper Function:

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

if (! function_exists('search')) {
    function search(Request $request = null)
    {
        // ... (unchanged code)

        foreach ($types as $type) {
            // ... (unchanged code)

            $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')
            ],
        ];
    }
}

In the helper function, you've enhanced the global search functionality. It takes a request object as an optional parameter, allowing flexibility. The function performs searches based on different types (user, profile) and supports pagination if requested.

Enum Update:

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,
        ];
    }
}

In the enum update, you've simplified the enum values, mapping search types directly to their respective model classes.

Your approach is elegant and provides a scalable solution for implementing a Global Search feature in Laravel. Well done!

Comments (0)

Comment


Note: All Input Fields are required.