Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Plastic Laravel Package

sleimanx2/plastic

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Installation Run composer require sleimanx2/plastic to add the package to your Laravel project. Publish the config file with php artisan vendor:publish --provider="Sleimanx2\Plastic\PlasticServiceProvider". Add the Elasticsearch connection to your .env:

    ELASTICSEARCH_CONNECTION=default
    ELASTICSEARCH_HOSTS=http://localhost:9200
    
  2. Basic Setup Define an Elasticsearch model by extending Sleimanx2\Plastic\ElasticModel:

    use Sleimanx2\Plastic\ElasticModel;
    
    class Product extends ElasticModel
    {
        protected $index = 'products';
        protected $type = '_doc';
    }
    
  3. First Query Use the fluent query builder to search:

    $results = Product::query()
        ->where('name', 'like', 'laptop%')
        ->paginate(10);
    
  4. Indexing a Model Sync a model with Elasticsearch:

    $product = Product::create(['name' => 'MacBook Pro', 'price' => 1999]);
    $product->syncToElastic(); // Manually sync
    // OR
    Product::observe(ElasticObserver::class); // Auto-sync on create/update
    

Implementation Patterns

Common Workflows

  1. Mapping Models Define mappings in a mappings() method:

    class Product extends ElasticModel
    {
        public function mappings()
        {
            return [
                'properties' => [
                    'name' => ['type' => 'text', 'analyzer' => 'english'],
                    'price' => ['type' => 'float'],
                    'tags' => ['type' => 'keyword'],
                ],
            ];
        }
    }
    

    Run php artisan plastic:mappings to apply mappings to Elasticsearch.

  2. Querying with Aggregations Use aggregations for analytics:

    $results = Product::query()
        ->terms('category', 'categories')
        ->paginate();
    
  3. Hybrid Search (SQL + Elasticsearch) Combine Laravel Eloquent with Elasticsearch queries:

    $products = Product::query()
        ->where('price', '>', 1000)
        ->elasticWhere('name', 'like', 'pro%')
        ->get();
    
  4. Bulk Operations Use bulkIndex() for efficient indexing:

    Product::bulkIndex([
        ['name' => 'Product A', 'price' => 100],
        ['name' => 'Product B', 'price' => 200],
    ]);
    
  5. Real-Time Updates Observe model events for auto-sync:

    class Product extends ElasticModel
    {
        protected static function booted()
        {
            static::observe(ElasticObserver::class);
        }
    }
    

Integration Tips

  • Laravel Scout Alternative: Use Plastic for advanced Elasticsearch features not covered by Scout (e.g., nested objects, custom analyzers).
  • Caching: Cache frequent queries with Laravel’s cache system:
    $cached = Cache::remember('products_search', now()->addHours(1), function () {
        return Product::query()->where('name', 'like', 'laptop%')->get();
    });
    
  • Testing: Use PlasticTestCase for testing:
    use Sleimanx2\Plastic\Testing\PlasticTestCase;
    
    class ProductTest extends PlasticTestCase
    {
        public function testSearch()
        {
            $this->assertCount(1, Product::query()->where('name', 'MacBook')->get());
        }
    }
    

Gotchas and Tips

Common Pitfalls

  1. Index/Type Confusion

    • Elasticsearch 7+ uses _doc as the default type. Ensure $type = '_doc' in your model.
    • Avoid deprecated type field in mappings (use properties instead).
  2. Mapping Conflicts

    • If mappings already exist, update them via:
      php artisan plastic:mappings --force
      
    • Use ->ignoreMappings() to skip mapping checks during queries.
  3. Connection Issues

    • Verify ELASTICSEARCH_HOSTS in .env includes the correct protocol (http:// or https://).
    • Use Plastic::connection('custom')->query(...) for multi-connection setups.
  4. Performance with Large Datasets

    • Use ->select(['field1', 'field2']) to limit returned fields.
    • For bulk operations, chunk data to avoid timeouts:
      Product::bulkIndex(array_chunk($products, 1000));
      
  5. Observer Conflicts

    • Ensure ElasticObserver is the last observer in the chain to avoid duplicate syncs.

Debugging Tips

  • Enable Logging Add to config/plastic.php:

    'log' => [
        'enabled' => true,
        'channel' => 'single',
    ],
    

    Check logs in storage/logs/laravel.log.

  • Query Inspection Use ->toElasticQuery() to see the raw Elasticsearch query:

    $query = Product::query()->where('name', 'like', 'pro%')->toElasticQuery();
    dd($query);
    
  • Reindexing Reindex all records with:

    php artisan plastic:reindex App\Models\Product
    

Extension Points

  1. Custom Analyzers Define analyzers in mappings():

    public function mappings()
    {
        return [
            'settings' => [
                'analysis' => [
                    'analyzer' => [
                        'custom_analyzer' => [
                            'type' => 'custom',
                            'tokenizer' => 'standard',
                            'filter' => ['lowercase', 'asciifolding'],
                        ],
                    ],
                ],
            ],
            'properties' => [
                'name' => ['type' => 'text', 'analyzer' => 'custom_analyzer'],
            ],
        ];
    }
    
  2. Custom Query Builders Extend Sleimanx2\Plastic\Query\Builder for domain-specific queries:

    class ProductQueryBuilder extends Builder
    {
        public function inStock()
        {
            return $this->where('stock', '>', 0);
        }
    }
    

    Bind it to your model:

    class Product extends ElasticModel
    {
        protected $queryBuilder = ProductQueryBuilder::class;
    }
    
  3. Hooks for Pre/Post Sync Override syncingToElastic() and syncedToElastic() in your model:

    protected function syncingToElastic(array $data)
    {
        $data['processed_at'] = now();
        return $data;
    }
    
  4. Multi-Tenancy Use dynamic indices based on tenant:

    class Product extends ElasticModel
    {
        protected $index = 'products_' . auth()->id();
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky