Skip to content
This repository was archived by the owner on Jul 31, 2018. It is now read-only.

Commit 5d91565

Browse files
GiamPy5maxiloc
authored and
maxiloc
committed
Adds onInsert callback to reindex() static call. (#87)
* Allows the usage of a callback in reindex() static call to access exactly which entity is being indexed to Algolia * Improves efficiency of onInsert callback * Actually updates the README. My bad.
1 parent 363f1b2 commit 5d91565

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

README.md

+11
Original file line numberDiff line numberDiff line change
@@ -402,6 +402,17 @@ To keep settings that you set on the Algolia dashboard when reindexing and setti
402402
Contact::reindex(true, true, true);
403403
```
404404

405+
To implement a callback that gets called everytime a batch of entities is indexed:
406+
407+
```php
408+
Contact::reindex(true, true, false, function ($entities)
409+
{
410+
foreach ($entities as $entity)
411+
{
412+
var_dump($entity->id); // Contact::$id
413+
}
414+
});
415+
```
405416

406417
### Clearing an Index
407418

src/AlgoliaEloquentTrait.php

+12-3
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ trait AlgoliaEloquentTrait
1818
* @param bool $setSettings
1919
* @param bool $mergeOldSettings
2020
*/
21-
public function _reindex($safe = true, $setSettings = true, $mergeOldSettings = false)
21+
public function _reindex($safe = true, $setSettings = true, $mergeOldSettings = false, \Closure $onInsert = null)
2222
{
2323
/** @var \AlgoliaSearch\Laravel\ModelHelper $modelHelper */
2424
$modelHelper = App::make('\AlgoliaSearch\Laravel\ModelHelper');
@@ -31,18 +31,27 @@ public function _reindex($safe = true, $setSettings = true, $mergeOldSettings =
3131
$this->_setSettings($setToTmpIndices, $mergeOldSettings);
3232
}
3333

34-
static::chunk(100, function ($models) use ($indicesTmp, $modelHelper) {
34+
static::chunk(100, function ($models) use ($indicesTmp, $modelHelper, $onInsert) {
3535
/** @var \AlgoliaSearch\Index $index */
3636
foreach ($indicesTmp as $index) {
37-
$records = [];
37+
$records = [];
38+
$recordsAsEntity = [];
3839

3940
foreach ($models as $model) {
4041
if ($modelHelper->indexOnly($model, $index->indexName)) {
4142
$records[] = $model->getAlgoliaRecordDefault($index->indexName);
43+
44+
if ($onInsert && is_callable($onInsert)) {
45+
$recordsAsEntity[] = $model;
46+
}
4247
}
4348
}
4449

4550
$index->addObjects($records);
51+
52+
if ($onInsert && is_callable($onInsert)) {
53+
call_user_func_array($onInsert, [$recordsAsEntity]);
54+
}
4655
}
4756

4857
});

0 commit comments

Comments
 (0)