PHPackages                             algolia/algoliasearch-laravel - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. algolia/algoliasearch-laravel

Abandoned → [laravel/scout](/?search=laravel%2Fscout)ArchivedLibrary[API Development](/categories/api)

algolia/algoliasearch-laravel
=============================

Laravel Algolia extension

1.7.1(9y ago)239318.5k↓50%51MITPHPPHP &gt;=5.5.9

Since Jun 12Pushed 8y ago80 watchersCompare

[ Source](https://github.com/algolia/algoliasearch-laravel)[ Packagist](https://packagist.org/packages/algolia/algoliasearch-laravel)[ RSS](/packages/algolia-algoliasearch-laravel/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (4)Versions (30)Used By (0)

\[DEPRECATED\] Algolia Search API Client for Laravel
====================================================

[](#deprecated-algolia-search-api-client-for-laravel)

[Algolia Search](https://www.algolia.com) is a hosted full-text, numerical, and faceted search engine capable of delivering realtime results from the first keystroke.

---

**This package is deprecated, we recommend you to use [Laravel Scout](https://laravel.com/docs/5.4/scout)**. If you want to extend Scout capabilities, please refer to [our dedicated documentation](https://www.algolia.com/doc/api-client/laravel/algolia-and-scout/)

---

[![Build Status](https://camo.githubusercontent.com/143cef03e4e7f86270030a3800a69e034fa0ef3b5b75b115eedd0c9792654c91/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f616c676f6c69612f616c676f6c69617365617263682d6c61726176656c2f6d61737465722e7376673f7374796c653d666c6174)](https://travis-ci.org/algolia/algoliasearch-laravel)[![Latest Version](https://camo.githubusercontent.com/078ad849ac37abd69b6ac631e0c57a1f4df1b82422d5a5734f986774177eb860/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f72656c656173652f616c676f6c69612f616c676f6c69617365617263682d6c61726176656c2e7376673f7374796c653d666c6174)](https://github.com/algolia/algoliasearch-laravel/releases)[![License](https://camo.githubusercontent.com/3de5ae6d37c1b4691e8aa672b9a5b2a788be6d66e185425ac0ae12eb1975139a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f616c676f6c69612f616c676f6c69617365617263682d6c61726176656c2e7376673f7374796c653d666c6174)](https://packagist.org/packages/algolia/algoliasearch-laravel)

This PHP package integrates the Algolia Search API into the Laravel Eloquent ORM. It's based on the [algoliasearch-client-php](https://github.com/algolia/algoliasearch-client-php) package.

**Note:** If you're using Laravel 4, checkout the [algoliasearch-laravel-4](https://github.com/algolia/algoliasearch-laravel-4) repository.

API Documentation
-----------------

[](#api-documentation)

You can find the full reference on [Algolia's website](https://www.algolia.com/doc/api-client/laravel/).

Table of Contents
-----------------

[](#table-of-contents)

1. **[Install](#install)**

    - [Install via composer](#install-via-composer)
    - [Service provider](#service-provider)
    - [Publish vendor](#publish-vendor)
2. **[Quick Start](#quick-start)**

    - [Quick Start](#quick-start)
    - [Ranking &amp; Relevance](#ranking--relevance)
    - [Frontend Search (realtime experience)](#frontend-search-realtime-experience)
    - [Backend Search](#backend-search)
3. **[Options](#options)**

    - [Auto-indexing &amp; Asynchronism](#auto-indexing--asynchronism)
    - [Custom Index Name](#custom-index-name)
    - [Per-environment Indexes](#per-environment-indexes)
    - [Custom `objectID`](#custom-objectid)
    - [Restrict Indexing to a Subset of Your Data](#restrict-indexing-to-a-subset-of-your-data)
4. **[Relationships](#relationships)**

    - [Relationships](#relationships)
5. **[Indexing](#indexing)**

    - [Manual Indexing](#manual-indexing)
    - [Manual Removal](#manual-removal)
    - [Reindexing](#reindexing)
    - [Clearing an Index](#clearing-an-index)
6. **[Manage indices](#manage-indices)**

    - [Primary/Replica](#primaryreplica)
    - [Target Multiple Indexes](#target-multiple-indexes)
7. **[Eloquent compatibility](#eloquent-compatibility)**

    - [Eloquent compatibility](#eloquent-compatibility)
    - [Compatibility](#compatibility)

Install
=======

[](#install)

Install via composer
--------------------

[](#install-via-composer)

Add `algolia/algoliasearch-laravel` to your `composer.json` file:

```
composer require algolia/algoliasearch-laravel
```

Service provider
----------------

[](#service-provider)

Add the service provider to `config/app.php` in the `providers` array.

```
AlgoliaSearch\Laravel\AlgoliaServiceProvider::class
```

Publish vendor
--------------

[](#publish-vendor)

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

```
php artisan vendor:publish
```

You can add the `--provider="Vinkla\Algolia\AlgoliaServiceProvider"` option to only publish assets of the Algolia package.

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.

Quick Start
===========

[](#quick-start)

Quick Start
-----------

[](#quick-start-1)

The following code adds search capabilities to your `Contact` model creating a `Contact` index:

```
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:

```
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:

```
Contact::reindex();
```

Ranking &amp; Relevance
-----------------------

[](#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:

```
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:

```
Contact::setSettings();
```

#### Synonyms

[](#synonyms)

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

Our [synonyms API](https://www.algolia.com/doc/relevance/synonyms) has been designed to manage as easily as possible a large set of synonyms for an index and its replicas.

You can use the synonyms API by adding a `synonyms` in `$algoliaSettings` class property like this:

```
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:

```
Contact::setSettings();
```

Frontend Search (realtime experience)
-------------------------------------

[](#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.

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](https://github.com/algolia/algoliasearch-client-javascript) 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.

In your JavaScript code you can do:

```
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 });
```

Backend Search
--------------

[](#backend-search)

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):

```
Contact::search('jon doe');
```

Options
=======

[](#options)

Auto-indexing &amp; Asynchronism
--------------------------------

[](#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.

You can disable the auto-indexing and auto-removing by setting the following options:

```
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.

```
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

```
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).

Custom Index Name
-----------------

[](#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:

```
use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
    use AlgoliaEloquentTrait;

    public $indices = ['contact_all'];
}
```

Per-environment Indexes
-----------------------

[](#per-environment-indexes)

You can suffix the index name with the current App environment using the following option:

```
use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
    use AlgoliaEloquentTrait;

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

Custom `objectID`
-----------------

[](#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).

```
use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
    use AlgoliaEloquentTrait;

    public static $objectIdKey = 'new_key';
}
```

Restrict Indexing to a Subset of Your Data
------------------------------------------

[](#restrict-indexing-to-a-subset-of-your-data)

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

```
use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
    use AlgoliaEloquentTrait;

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

Relationships
=============

[](#relationships)

Relationships
-------------

[](#relationships-1)

By default the Algolia package will fetch the **loaded** relationships.

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.

It will look like:

```
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:

```
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
========

[](#indexing)

Visibility
----------

[](#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.

```
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.

Manual Indexing
---------------

[](#manual-indexing)

You can trigger indexing using the `pushToIndex` instance method.

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

Manual Removal
--------------

[](#manual-removal)

And trigger the removal using the `removeFromIndex` instance method.

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

Reindexing
----------

[](#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:

```
Contact::reindex();
```

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

```
Contact::reindex(false);
```

To set settings during the reindexing process:

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

To keep settings that you set on the Algolia dashboard when reindexing and changing settings:

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

To implement a callback that gets called everytime a batch of entities is indexed:

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

Clearing an Index
-----------------

[](#clearing-an-index)

To clear an index, use the `clearIndices` class method:

```
Contact::clearIndices();
```

Manage indices
==============

[](#manage-indices)

Primary/Replica
---------------

[](#primaryreplica)

You can define replica indexes using the `$algolia_settings` variable:

```
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:

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

Target Multiple Indexes
-----------------------

[](#target-multiple-indexes)

You can index a record in several indexes using the `$indices` property:

```
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:

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

Eloquent compatibility
======================

[](#eloquent-compatibility)

Eloquent compatibility
----------------------

[](#eloquent-compatibility-1)

Doing:

```
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.

To make this query work with Algolia you need to do it like this:

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

Compatibility
-------------

[](#compatibility)

Compatible with 5.x applications

###  Health Score

45

—

FairBetter than 93% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity49

Moderate usage in the ecosystem

Community33

Small or concentrated contributor base

Maturity69

Established project with proven stability

 Bus Factor1

Top contributor holds 51% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~26 days

Recently: every ~21 days

Total

24

Last Release

3395d ago

Major Versions

1.0.4 → 4.2.x-dev2015-09-28

PHP version history (2 changes)1.0.0PHP &gt;=5.5.9

4.2.x-devPHP &gt;=5.3.29

### Community

Maintainers

![](https://www.gravatar.com/avatar/b6d048f4c846e591bf24f521537e3ba9ba6ee1e0d7e466714c346c1a4cf7b576?d=identicon)[maxiloc](/maintainers/maxiloc)

![](https://www.gravatar.com/avatar/dd7b3a0ca4d58fca8b57cfd28ac17cb1e37b5fc6f92376b725a9d22f3d94379e?d=identicon)[julienbourdeau](/maintainers/julienbourdeau)

---

Top Contributors

[![maxiloc](https://avatars.githubusercontent.com/u/1689007?v=4)](https://github.com/maxiloc "maxiloc (78 commits)")[![vinkla](https://avatars.githubusercontent.com/u/499192?v=4)](https://github.com/vinkla "vinkla (18 commits)")[![algoliareadmebot](https://avatars.githubusercontent.com/u/18572634?v=4)](https://github.com/algoliareadmebot "algoliareadmebot (9 commits)")[![rayrutjes](https://avatars.githubusercontent.com/u/5570853?v=4)](https://github.com/rayrutjes "rayrutjes (7 commits)")[![zyml](https://avatars.githubusercontent.com/u/1495648?v=4)](https://github.com/zyml "zyml (7 commits)")[![julienbourdeau](https://avatars.githubusercontent.com/u/1525636?v=4)](https://github.com/julienbourdeau "julienbourdeau (6 commits)")[![JanPetr](https://avatars.githubusercontent.com/u/1058144?v=4)](https://github.com/JanPetr "JanPetr (4 commits)")[![redox](https://avatars.githubusercontent.com/u/29529?v=4)](https://github.com/redox "redox (3 commits)")[![nikita240](https://avatars.githubusercontent.com/u/6479817?v=4)](https://github.com/nikita240 "nikita240 (3 commits)")[![GiamPy5](https://avatars.githubusercontent.com/u/4460702?v=4)](https://github.com/GiamPy5 "GiamPy5 (2 commits)")[![harrisbp](https://avatars.githubusercontent.com/u/10454950?v=4)](https://github.com/harrisbp "harrisbp (2 commits)")[![seafoox](https://avatars.githubusercontent.com/u/1101220?v=4)](https://github.com/seafoox "seafoox (1 commits)")[![speedblue](https://avatars.githubusercontent.com/u/555866?v=4)](https://github.com/speedblue "speedblue (1 commits)")[![wlkns](https://avatars.githubusercontent.com/u/1921583?v=4)](https://github.com/wlkns "wlkns (1 commits)")[![joshforbes](https://avatars.githubusercontent.com/u/3682518?v=4)](https://github.com/joshforbes "joshforbes (1 commits)")[![bobylito](https://avatars.githubusercontent.com/u/393765?v=4)](https://github.com/bobylito "bobylito (1 commits)")[![codeharmonics](https://avatars.githubusercontent.com/u/6850012?v=4)](https://github.com/codeharmonics "codeharmonics (1 commits)")[![code-poel](https://avatars.githubusercontent.com/u/525901?v=4)](https://github.com/code-poel "code-poel (1 commits)")[![FelixMalfait](https://avatars.githubusercontent.com/u/6399865?v=4)](https://github.com/FelixMalfait "FelixMalfait (1 commits)")[![freekmurze](https://avatars.githubusercontent.com/u/483853?v=4)](https://github.com/freekmurze "freekmurze (1 commits)")

---

Tags

algolia-searchlaravelphpsearch-engineapisearchlaravelalgolia

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/algolia-algoliasearch-laravel/health.svg)

```
[![Health](https://phpackages.com/badges/algolia-algoliasearch-laravel/health.svg)](https://phpackages.com/packages/algolia-algoliasearch-laravel)
```

###  Alternatives

[algolia/algoliasearch-client-php

API powering the features of Algolia.

69433.0M114](/packages/algolia-algoliasearch-client-php)[aerni/laravel-spotify

A Laravel wrapper for the Spotify Web API

209145.6k](/packages/aerni-laravel-spotify)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
