Laravel Home Services Project - Search Services
In this video, we will learn about implementing search services in our Laravel project.
Let's see how we can make the home page search box work.
First, we need to create a controller.
To do this, switch to the command prompt and run the following command to create the controller:
php artisan make:controller SearchController
Now, switch to the project and open the SearchController file.
Here, let's create functions for autocomplete and search services.
In the SearchController file, write the following code:
<?php
namespace App\Http\Controllers;
use App\Models\Service;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
class SearchController extends Controller
{
public function autocomplete(Request $req)
{
$data = Service::select('name')->where("name","LIKE","%{$req->input('query')}%")->get();
return response()->json($data);
}
public function searchService(Request $req)
{
$service_slug = Str::slug($req->q,'-');
if($service_slug)
{
return redirect('/service/'.$service_slug);
}
else
{
return back();
}
}
}
Next, go to the web.php file and create a route by writing the following code:
Route::get('/autocomplete',[SearchController::class,'autocomplete'])->name('autocomplete');
Route::post('/search',[SearchController::class,'searchService'])->name('searchService');
Now, go to the base.blade.php layout file and add the @stack directive before @livewireScripts:
@stack('scripts')
@livewireScripts
Next, go to the home-component.blade.php view file and add the following code at the bottom of the page:
@push('scripts')
<script type="text/javascript">
var path = "{{route('autocomplete')}}";
$('input.typeahead').typeahead({
source: function(query,process){
return $.get(path,{query:query},function(data){
return process(data);
});
}
});
</script>
@endpush
And inside the search form, add the action and also add @csrf as follows:
<div class="filter-title">
<div class="title-header">
<h2 style="color:#fff;">BOOK A SERVICE</h2>
<p class="lead">Book a service at very affordable price, </p>
</div>
<div class="filter-header">
<form id="sform" action="{{route('searchService')}}" method="post">
@csrf
<input type="text" id="q" name="q" required="required" placeholder="What Services do you want?"
class="input-large typeahead" autocomplete="off">
<input type="submit" name="submit" value="Search">
</form>
</div>
</div>
Now, it's done. Let's check the result.
Switch to the browser and refresh the page.
In the search box, type any service name you want to search for.
As you type, you will see auto-populated services. Select any service from this list and click on search.
Now, you will see the service details of the searched service.
So, in this way, you can create a search box for services.