Today, I had a request, to improve how searching should work in the application which my team currently working on. The searching mechanism that implemented at the moment, is kind of slow - I can say performance issue.

get('/search', function (Request $request) { return match($request->type) { 'user' => User::search($request->search)->first(), 'post' => Post::search($request->search)->first(), }}); But it's kind of, hard to maintain in future, too many hardcoded in this route.

So your new route will be: use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; Route::middleware('auth:sanctum')->get('/search', function (Request $request) { return search( $request->type, $request->search, $request->query('paginate', false)); }); BUT!

How I, I make use of Laravel Enum by Spatie, and my route will be like the following: get('/search', function (Request $request) { abort_if( empty($request->type) || empty(SearchType::tryFrom($request->type)), 404, 'Unknown search type' ); abort_if( empty($request->search), 404, 'Please provide search keyword' ); return search(SearchType::tryFrom($request->type), $request->search, $request->query('paginate', false)); }); Where the SearchType: \App\Models\User::class, 'profile' => \Profile\Models\Profile::class, ]; } protected static function labels(): array { return [ 'user' => __('User'), 'profile' => __('Profile'), ]; }}
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Community Partners