Laravel Projects Examples

Laravel Search by Query/Tag With Auto Complete - Laravel Scout and Alpine.js

This project demonstrates how to add search with suggestions using Laravel Scout and Alpine.js.

How It Works

For this example, a database scout driver is used.

// ...
 
SCOUT_DRIVER=database

The Searchable trait must be added to the Eloquent models from which search you will want to do. A good practice would be to add searchable fields to the toSearchableArray() method as an array in the model.

app/Models/Category.php:

use Laravel\Scout\Searchable;
use Illuminate\Database\Eloquent\Model;
 
class Category extends Model
{
use Searchable;
 
// ...
 
public function toSearchableArray(): array
{
return [
'id' => $this->id,
'name' => $this->name,
];
}
}

app/Models/Product.php:

use Laravel\Scout\Searchable;
use Illuminate\Database\Eloquent\Model;
 
class Product extends Model
{
use Searchable;
 
// ...
 
public function toSearchableArray(): array
{
return [
'id' => $this->id,
'title' => $this->title,
'code' => $this->code,
];
}
}

Next, we will:

  • Set up the Search Blade component
  • Set up the Search Controller