2017 © Pedro Peláez
 

library algoliasearch-laravel

Laravel Algolia extension

image

algolia/algoliasearch-laravel

Laravel Algolia extension

  • Monday, March 5, 2018
  • by maxiloc
  • Repository
  • 52 Watchers
  • 236 Stars
  • 233,180 Installations
  • PHP
  • 0 Dependents
  • 0 Suggesters
  • 61 Forks
  • 1 Open issues
  • 30 Versions
  • 4 % Grown

The README.md

[DEPRECATED] Algolia Search API Client for Laravel

Algolia Search is a hosted full-text, numerical, and faceted search engine capable of delivering realtime results from the first keystroke., (*1)


This package is deprecated, we recommend you to use Laravel Scout. If you want to extend Scout capabilities, please refer to our dedicated documentation, (*2)


Build Status Latest Version License, (*3)

This PHP package integrates the Algolia Search API into the Laravel Eloquent ORM. It's based on the algoliasearch-client-php package., (*4)

Note: If you're using Laravel 4, checkout the algoliasearch-laravel-4 repository., (*5)

API Documentation

You can find the full reference on Algolia's website., (*6)

Table of Contents

  1. Install, (*7)

  2. Quick Start, (*8)

  3. Options, (*9)

  4. Relationships, (*10)

  5. Indexing, (*11)

  6. Manage indices, (*12)

  7. Eloquent compatibility, (*13)

Install

Install via composer

Add algolia/algoliasearch-laravel to your composer.json file:, (*14)

composer require algolia/algoliasearch-laravel

Service provider

Add the service provider to config/app.php in the providers array., (*15)

AlgoliaSearch\Laravel\AlgoliaServiceProvider::class

Publish vendor

Laravel Algolia requires a connection configuration. To get started, you'll need to publish all vendor assets:, (*16)

php artisan vendor:publish

You can add the --provider="Vinkla\Algolia\AlgoliaServiceProvider" option to only publish assets of the Algolia package., (*17)

This will create a config/algolia.php file in your app that you can modify to set your configuration. Also, make sure you check for changes compared to the original config file after an upgrade., (*18)

Quick Start

Quick Start

The following code adds search capabilities to your Contact model creating a Contact index:, (*19)

use Illuminate\Database\Eloquent\Model;
use AlgoliaSearch\Laravel\AlgoliaEloquentTrait;

class Contact extends Model
{
    use AlgoliaEloquentTrait;
}

By default all visible attributes are sent. If you want to send specific attributes you can do something like:, (*20)

use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
    use AlgoliaEloquentTrait;

    public function getAlgoliaRecord()
    {
        return array_merge($this->toArray(), [
            'custom_name' => 'Custom Name'
        ]);
    }
}

After setting up your model, you need to manually do an initial import of your data. You can do this by calling reindex on your model class. Using our previous example, this would be:, (*21)

Contact::reindex();

Ranking & Relevance

We provide many ways to configure your index settings to tune the overall relevancy, but the most important ones are the searchable attributes and the attributes reflecting the record popularity. You can configure them with the following code:, (*22)

use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
    use AlgoliaEloquentTrait;

    public $algoliaSettings = [
        'searchableAttributes' => [
            'id',
            'name',
        ],
        'customRanking' => [
            'desc(popularity)',
            'asc(name)',
        ],
    ];
}

You can propagate (save) the settings to algolia by using the setSetting method:, (*23)

Contact::setSettings();

Synonyms

Synonyms are used to tell the engine about words or expressions that should be considered equal in regard to the textual relevance., (*24)

Our synonyms API has been designed to manage as easily as possible a large set of synonyms for an index and its replicas., (*25)

You can use the synonyms API by adding a synonyms in $algoliaSettings class property like this:, (*26)

use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
    use AlgoliaEloquentTrait;

    public $algoliaSettings = [
        'synonyms' => [
            [
                'objectID' => 'red-color',
                'type'     => 'synonym',
                'synonyms' => ['red', 'another red', 'yet another red']
            ]
        ]
    ];
}

You can propagate (save) the settings to algolia using the setSetting method:, (*27)

Contact::setSettings();

Frontend Search (realtime experience)

Traditional search implementations tend to have search logic and functionality on the backend. This made sense when the search experience consisted of a user entering a search query, executing that search, and then being redirected to a search result page., (*28)

Implementing search on the backend is no longer necessary. In fact, in most cases it is harmful to performance because of the extra network and processing latency. We highly recommend the usage of our JavaScript API Client issuing all search requests directly from the end user's browser, mobile device, or client. It will reduce the overall search latency while offloading your servers at the same time., (*29)

In your JavaScript code you can do:, (*30)

var client = algoliasearch('ApplicationID', 'Search-Only-API-Key');
var index = client.initIndex('YourIndexName');
index.search('something', function(success, hits) {
  console.log(success, hits)
}, { hitsPerPage: 10, page: 0 });

You could also use the search method, but it's not recommended to implement an instant/realtime search experience from the backend (having a frontend search gives a better user experience):, (*31)

Contact::search('jon doe');

Options

Auto-indexing & Asynchronism

Each time a record is saved; it will be - asynchronously - indexed. On the other hand, each time a record is destroyed, it will be - asynchronously - removed from the index., (*32)

You can disable the auto-indexing and auto-removing by setting the following options:, (*33)

use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
    use AlgoliaEloquentTrait;

    public static $autoIndex = false;
    public static $autoDelete = false;
}

You can temporarily disable auto-indexing. This is often done for performance reasons., (*34)

Contact::$autoIndex = false;
Contact::clearIndices();

for ($i = 0; $i < 10000; $i++) {
    $contact = Contact::firstOrCreate(['name' => 'Jean']);
}

Contact::reindex(); // Will use batch operations.
Contact::$autoIndex = true;

You can also make a dynamic condition for those two parameters by creating an autoIndex and/or autoDelete method on your model, (*35)

use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
    use AlgoliaEloquentTrait;

    public function autoIndex()
    {
        if (\App::environment() === 'test') {
            return false;
        }

        return true;
    }

    public static autoDelete()
    {
        if (\App::environment() === 'test') {
            return false;
        }

        return true;
    }
}

Be careful to define those two methods in AlgoliaEloquentTrait. When putting those methods in a parent class they will be "erased" by AlgoliaEloquentTrait if used in a child class (because of php inheritance)., (*36)

Custom Index Name

By default, the index name will be the pluralized class name, e.g. "Contacts". You can customize the index name by using the $indices option:, (*37)

use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
    use AlgoliaEloquentTrait;

    public $indices = ['contact_all'];
}

Per-environment Indexes

You can suffix the index name with the current App environment using the following option:, (*38)

use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
    use AlgoliaEloquentTrait;

    public static $perEnvironment = true; // Index name will be 'Contacts_{\App::environnement()}';
}

Custom objectID

By default, the objectID is based on your record's keyName (id by default). You can change this behavior specifying the objectIdKey option (be sure to use a uniq field)., (*39)

use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
    use AlgoliaEloquentTrait;

    public static $objectIdKey = 'new_key';
}

Restrict Indexing to a Subset of Your Data

You can add constraints controlling if a record must be indexed by defining the indexOnly() method., (*40)

use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
    use AlgoliaEloquentTrait;

    public function indexOnly($index_name)
    {
        return (bool) $condition;
    }
}

Relationships

Relationships

By default the Algolia package will fetch the loaded relationships., (*41)

If you want to index records that haven't yet loaded any relations, you can do it by loading them in the getAlgoliaRecord that you can create in your model., (*42)

It will look like:, (*43)

public function getAlgoliaRecord()
{
    /**
     * Load the categories relation so that it's available
     *  in the laravel toArray method
     */
    $this->categories;

   return $this->toArray();
}

In the resulted object, you will have categories converted to array by Laravel. If you want a custom relation structure you will instead do something like:, (*44)

public function getAlgoliaRecord()
{
    /**
     * Load the categories relation so that it's available
     *  in the laravel toArray method
     */
    $extra_data = [];
    $extra_data['categories'] = array_map(function ($data) {
                                        return $data['name'];
                                }, $this->categories->toArray());

   return array_merge($this->toArray(), $extra_data);
}

Indexing

Visibility

By default, Algolia will only be able to access visible attributes of your model. So, for example, you will receive a No content in PUT request exception when using this example code, because invisible_attribute key returns an empty/null variable., (*45)

protected $visible = ['visible_attribute', 'other_visible_attribute'];

public function getAlgoliaRecord()
{
    return [
        'invisible_attribute' => $this->invisible_attribute
    ];
}

Before Indexing, be sure to have correctly listed your visible attributes. To bypass this safety mask imposed by Laravel, you may use $this->attributes['invisible_attribute'] to access directly to the attribute even if is not visible, but the recommendation is to avoid this type of access to attributes in your Model., (*46)

Manual Indexing

You can trigger indexing using the pushToIndex instance method., (*47)

$contact = Contact::firstOrCreate(['name' => 'Jean']);
$contact->pushToIndex();

Manual Removal

And trigger the removal using the removeFromIndex instance method., (*48)

$contact = Contact::firstOrCreate(['name' => 'Jean']);
$contact->removeFromIndex();

Reindexing

To safely reindex all your records (index to a temporary index + move the temporary index to the current one atomically), use the reindex class method:, (*49)

Contact::reindex();

To reindex all your records (in place, without deleting outdated records):, (*50)

Contact::reindex(false);

To set settings during the reindexing process:, (*51)

Contact::reindex(true, true);

To keep settings that you set on the Algolia dashboard when reindexing and changing settings:, (*52)

Contact::reindex(true, true, true);

To implement a callback that gets called everytime a batch of entities is indexed:, (*53)

Contact::reindex(true, true, false, function ($entities)
{
    foreach ($entities as $entity)
    {
        var_dump($entity->id); // Contact::$id
    }
});

Clearing an Index

To clear an index, use the clearIndices class method:, (*54)

Contact::clearIndices();

Manage indices

Primary/Replica

You can define replica indexes using the $algolia_settings variable:, (*55)

use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
     use AlgoliaEloquentTrait;

     public $algoliaSettings = [
        'searchableAttributes' => [
            'id',
            'name',
        ],
        'customRanking' => [
            'desc(popularity)',
            'asc(name)',
        ],
        'replicas' => [
            'contacts_desc',
        ],
    ];

    public $replicasSettings = [
        'contacts_desc' => [
            'ranking' => [
                'desc(name)',
                'typo',
                'geo',
                'words',
                'proximity',
                'attribute',
                'exact',
                'custom'
            ]
        ]
    ];
}

To search using a replica, use the following code:, (*56)

Book::search('foo bar', ['index' => 'contacts_desc']);

Target Multiple Indexes

You can index a record in several indexes using the $indices property:, (*57)

use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
    use AlgoliaEloquentTrait;

    public $indices = [
        'contact_public',
        'contact_private',
    ];

    public function indexOnly($indexName)
    {
        if ($indexName == 'contact_public')
            return true;

        return $this->private;
    }

}

To search using an extra index, use the following code:, (*58)

Book::search('foo bar', ['index' => 'contacts_private']);

Eloquent compatibility

Eloquent compatibility

Doing:, (*59)

Ad::where('id', $id)->update($attributes);

will not trigger anything in the model (so no update will happen in Algolia). This is because it is not an Eloquent call. It is just a convenient way to generate the query hidden behind the model., (*60)

To make this query work with Algolia you need to do it like this:, (*61)

Ad::find($id)->update($attributes);

Compatibility

Compatible with 5.x applications, (*62)

The Versions

05/03 2018

dev-master

9999999-dev

Laravel Algolia extension

  Sources   Download

MIT

The Requires

 

The Development Requires

laravel api search algolia

31/01 2017

1.7.1

1.7.1.0

Laravel Algolia extension

  Sources   Download

MIT

The Requires

 

The Development Requires

laravel api search algolia

17/11 2016

1.7.0

1.7.0.0

Laravel Algolia extension

  Sources   Download

MIT

The Requires

 

The Development Requires

laravel api search algolia

16/11 2016

1.6.1

1.6.1.0

Laravel Algolia extension

  Sources   Download

MIT

The Requires

 

The Development Requires

laravel api search algolia

09/11 2016

1.6.0

1.6.0.0

Laravel Algolia extension

  Sources   Download

MIT

The Requires

 

The Development Requires

laravel api search algolia

07/11 2016

1.5.0

1.5.0.0

Laravel Algolia extension

  Sources   Download

MIT

The Requires

 

The Development Requires

laravel api search algolia

07/11 2016

1.4.0

1.4.0.0

Laravel Algolia extension

  Sources   Download

MIT

The Requires

 

The Development Requires

laravel api search algolia

20/10 2016

dev-feat/temporaryDisableIndexing

dev-feat/temporaryDisableIndexing

Laravel Algolia extension

  Sources   Download

MIT

The Requires

 

The Development Requires

laravel api search algolia

17/10 2016

1.3.0

1.3.0.0

Laravel Algolia extension

  Sources   Download

MIT

The Requires

 

The Development Requires

laravel api search algolia

03/10 2016

dev-slaves-replicas-renaming

dev-slaves-replicas-renaming

Laravel Algolia extension

  Sources   Download

MIT

The Requires

 

The Development Requires

laravel api search algolia

09/09 2016

dev-getting-started-reindex

dev-getting-started-reindex

Laravel Algolia extension

  Sources   Download

MIT

The Requires

 

The Development Requires

laravel api search algolia

22/08 2016

dev-fix_slaves

dev-fix_slaves

Laravel Algolia extension

  Sources   Download

MIT

The Requires

 

The Development Requires

laravel api search algolia

22/08 2016

1.2.2

1.2.2.0

Laravel Algolia extension

  Sources   Download

MIT

The Requires

 

The Development Requires

laravel api search algolia

02/08 2016

1.2.1

1.2.1.0

Laravel Algolia extension

  Sources   Download

MIT

The Requires

 

The Development Requires

laravel api search algolia

23/06 2016

1.2.0

1.2.0.0

Laravel Algolia extension

  Sources   Download

MIT

The Requires

 

The Development Requires

laravel api search algolia

23/06 2016

1.1.1

1.1.1.0

Laravel Algolia extension

  Sources   Download

MIT

The Requires

 

The Development Requires

laravel api search algolia

03/05 2016

1.1.0

1.1.0.0

Laravel Algolia extension

  Sources   Download

MIT

The Requires

 

The Development Requires

laravel api search algolia

03/05 2016

dev-custom-auto-index-and-delete

dev-custom-auto-index-and-delete

Laravel Algolia extension

  Sources   Download

MIT

The Requires

 

The Development Requires

laravel api search algolia

11/02 2016

1.0.10

1.0.10.0

Laravel Algolia extension

  Sources   Download

MIT

The Requires

 

The Development Requires

laravel api search algolia

25/01 2016

1.0.9

1.0.9.0

Laravel Algolia extension

  Sources   Download

MIT

The Requires

 

The Development Requires

laravel api search algolia

18/11 2015

1.0.8

1.0.8.0

Laravel Algolia extension

  Sources   Download

MIT

The Requires

 

The Development Requires

laravel api search algolia

14/11 2015

1.0.7

1.0.7.0

Laravel Algolia extension

  Sources   Download

MIT

The Requires

 

The Development Requires

laravel api search algolia

27/10 2015

1.0.6

1.0.6.0

Laravel Algolia extension

  Sources   Download

MIT

The Requires

 

The Development Requires

laravel api search algolia

27/10 2015

1.0.5

1.0.5.0

Laravel Algolia extension

  Sources   Download

MIT

The Requires

 

The Development Requires

laravel api search algolia

28/09 2015

4.2.x-dev

4.2.9999999.9999999-dev

Laravel Algolia extension

  Sources   Download

MIT

The Requires

 

The Development Requires

laravel api search algolia

21/09 2015

1.0.4

1.0.4.0

Laravel Algolia extension

  Sources   Download

MIT

The Requires

 

The Development Requires

laravel api search algolia

07/07 2015

1.0.3

1.0.3.0

Laravel Algolia extension

  Sources   Download

MIT

The Requires

 

The Development Requires

laravel api search algolia

30/06 2015

1.0.2

1.0.2.0

Laravel Algolia extension

  Sources   Download

MIT

The Requires

 

The Development Requires

laravel api search algolia

18/06 2015

1.0.1

1.0.1.0

Laravel Algolia extension

  Sources   Download

MIT

The Requires

 

The Development Requires

laravel api search algolia

12/06 2015

1.0.0

1.0.0.0

Laravel Algolia extension

  Sources   Download

MIT

The Requires

 

The Development Requires

laravel api search algolia