1. Go to this page and download the library: Download glueful/meilisearch library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
class Store extends Model implements SearchableInterface
{
use Searchable;
public function toSearchableArray(): array
{
return [
'id' => $this->uuid,
'name' => $this->name,
'_geo' => [
'lat' => (float) $this->latitude,
'lng' => (float) $this->longitude,
],
];
}
public function getSearchableFilterableAttributes(): array
{
return ['_geo', 'category'];
}
public function getSearchableSortableAttributes(): array
{
return ['_geo', 'name'];
}
}
// Find stores within 5km of a point
$results = Store::search($context, 'coffee')
->whereGeoRadius(40.7128, -74.0060, 5000)
->get();
// Find within bounding box
$results = Store::search($context, '')
->whereGeoBoundingBox([45.0, -73.0], [40.0, -74.0])
->get();
// Sort by distance (nearest first)
$results = Store::search($context, 'coffee')
->orderByGeo(40.7128, -74.0060, 'asc')
->get();
$results = Post::search($context, 'important topic')
->highlight(['title', 'body'])
->get();
// Access highlighted results in raw hits
$rawResults = Post::search($context, 'important')->highlight(['title'])->raw();
foreach ($rawResults['hits'] as $hit) {
echo $hit['_formatted']['title']; // Contains <em>important</em>
}
// Index a single model
$post = Post::find($context, $uuid);
$post->searchableSync();
// Remove from index
$post->searchableRemove();
// Batch indexing via BatchIndexer
$indexer = app($context, BatchIndexer::class);
$posts = Post::query($context)->where('status', 'published')->get();
$indexer->indexMany($posts);
use Glueful\Extensions\Meilisearch\Indexing\IndexManager;
$manager = app($context, IndexManager::class);
// Create index with settings
$manager->createIndex('posts');
// Update index settings
$manager->updateSettings('posts', [
'filterableAttributes' => ['status', 'category'],
'sortableAttributes' => ['published_at', 'title'],
'searchableAttributes' => ['title', 'body', 'tags'],
]);
// Sync settings from model
$manager->syncSettingsForModel(new Post([], $context));
// Get index statistics
$stats = $manager->getStats('posts');
// Delete all documents from index
$manager->flush('posts');
// Delete the index entirely
$manager->deleteIndex('posts');
// Using db() helper with transaction()
db($context)->transaction(function () use ($context) {
$post = Post::create($context, [
'title' => 'New Post',
'body' => 'Content here...',
]);
// Indexing is deferred, not executed yet
});
// After commit, the post is indexed
// If transaction rolls back, nothing is indexed
try {
db($context)->transaction(function () use ($context) {
$post = Post::create($context, ['title' => 'Will be rolled back']);
throw new \Exception('Rollback!');
});
} catch (\Exception $e) {
// Transaction rolled back - post is NOT indexed
}