PHP code example of babak-rostami / elasticsearch-laravel

1. Go to this page and download the library: Download babak-rostami/elasticsearch-laravel 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/ */

    

babak-rostami / elasticsearch-laravel example snippets


composer 

php artisan vendor:publish --tag=elasticsearch-config



namespace App\Models;

use Babak\Elasticsearch\Traits\ElasticsearchableTrait;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use ElasticsearchableTrait;

    protected static function elasticsearchProperties(): array
    {
        return [
            'title' => [
                'type' => 'text',
                'analyzer' => 'autocomplete_index',
                'search_analyzer' => 'autocomplete_search',
            ]
        ];
    }


    protected static function elasticsearchFields(): array
    {
        return ['title'];
    }

    public static function elasticsearchIndex(): string
    {
        return 'posts';
    }
}


Post::createElasticIndex();

Elasticsearch::sync($post);

$post = new Post();
$post->title = 'New title';
$post->body = 'laravel elasticsearch search';
$post->save();

Elasticsearch::sync($post);

Elasticsearch::update($post, [
    'title' => 'Updated title'
]);

$post->delete();
Elasticsearch::delete($post);

Elasticsearch::bulkIndex(Post::all());

$results = Post::searchElastic('how to use elastic search in laravel');

Elasticsearch::sync($model);
Elasticsearch::delete($model);
Elasticsearch::createIndex($index, $mapping);
Elasticsearch::deleteIndex($index);
bash
php artisan elasticsearch:index