Skip to content

Commit

Permalink
Update docs to explain collection hydration
Browse files Browse the repository at this point in the history
  • Loading branch information
f-liva committed Nov 24, 2016
1 parent d67b2d6 commit f59edcd
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 f59edcd

Please sign in to comment.