Skip to content

Commit ea6bc5e

Browse files
authored
Adding hydrate Macro
Adding hydrate macro to allow for model hydration from the algolia index. @aaronhuisinga suggestion of un-guarding first has been added.
1 parent d41ce50 commit ea6bc5e

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

src/macros.php

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
<?php
22

33
use Laravel\Scout\Builder;
4+
use Illuminate\Database\Eloquent\Collection;
45

56

67
if (! Builder::hasMacro('count')) {
@@ -81,3 +82,34 @@
8182
return $this;
8283
});
8384
}
85+
86+
if (! Builder::hasMacro('hydrate')) {
87+
/**
88+
* get() hydrates records by looking up the Ids in the corresponding database
89+
* This macro uses the data returned from the search results to hydrate
90+
* the models and return a collection
91+
*
92+
* @return Collection
93+
*/
94+
Builder::macro('hydrate', function () {
95+
$results = $this->engine()->search($this);
96+
97+
if (count($results['hits']) === 0) {
98+
return Collection::make();
99+
}
100+
101+
$hits = collect($results['hits']);
102+
$className = get_class($this->model);
103+
$models = new Collection();
104+
105+
Eloquent::unguard();
106+
107+
$hits->each(function($item, $key) use ($className, $models) {
108+
$models->push(new $className($item));
109+
});
110+
111+
Eloquent::reguard();
112+
113+
return $models;
114+
});
115+
}

0 commit comments

Comments
 (0)