Skip to content

Commit

Permalink
Merge pull request #61 from fede91it/master
Browse files Browse the repository at this point in the history
Update docs to explain collection hydration
  • Loading branch information
TomLingham authored Nov 25, 2016
2 parents d67b2d6 + f59edcd commit fbe64c6
Showing 1 changed file with 3 additions and 6 deletions.
9 changes: 3 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -120,16 +120,13 @@ This will, however, also return the `relevance` aliased column regardless of wha

## How to get a Laravel Eloquent Collection

Transforming the search results into a collection of Laravel Eloquent models is outside the scope of this project. However, an easy way to achieve this without hitting your database more than necessary is to use the Eloquent `fill()` method.
Transforming the search results into a collection of Laravel Eloquent models is outside the scope of this project. However, an easy way to achieve this without hitting your database more than necessary is to use the Eloquent `hydrate()` method.

```php
$users = collect(array_map(function($result) {
return (new \App\User())->forceFill(get_object_vars($result));
}, Searchy::users('name', 'email')->query('Andrew')->get()));
\App\User::hydrate(Searchy::users('name', 'email')->query('Andrew')->get());
```

All this does is map a function over the Searchy results and then creates a new instance of the User model and hydrates the model using the `forceFill()` method.
Then once it has an array of all the Eloquent User models, it simply uses the Laravel `collect()` method to return the array as Laravel Collection which is the same as you would receive from querying the Laravel model directly. `get_object_vars()` is simply a PHP method to extract the accessible object variables as an associative array.
This method creates a collection of models from a plain arrays. This is just our case because Searchy results are provided as arrays, and using `hydrate` we will converted them to instances of `User` model.

## Unicode Characters Support

Expand Down

0 comments on commit fbe64c6

Please sign in to comment.