I am fetching out all my suppliers from my database using:
$q = Input::get('filter');
$Supplier = new Supplier;
$data = $Supplier->where('name', 'LIKE', '%'.$q['filters'][0]['value'].'%')->get();
I then want the user to be able to filter further but without having to query the database again for every filter they apply.
For instance, of the data returned from the query, one of the columns is supplier_type_id. In the UI the user has the ability to filter the suppliers that were brought back by supplier type e.g. tick a box next to food suppliers and it further filters down the results without touching the database.
So really I want to filter the $data object that has come back from Laravel.
How can I do this?
If you want to filter the collection after the request that queried the database is over, then that's something you should be tackling on client side.
The variable $data
is available only on the server side. To persist the data from one request to another on the server, you would have to store it in the current session (using Session::put()
and Session::get()
) or cache it in some way. That's not really good in most cases, because any changes to the database will lead to inconsistencies between the storage data and the session data.
The best solution for handling this without touching the database, would be to send the data (possibily in JSON format) and then use JavaScript to handle any additional filtering inside the UI.
Caching your query results for a specified amount of time can be done using the remember
method:
$data = $Supplier->where('name', 'LIKE', '%'.$q['filters'][0]['value'].'%')->remember(60)->get();
In the example above, the query results will be cached for one hour, so any requests within that hour will fetch the data from the cache not from the database. You can see the Caching Queries and Cache configuration and usage Laravel documentation for more info.
You can then filter the cached collection even more with a filter
closure:
$supplierTypeId = Input::get('supplier_type_id');
$data = $data->filter(function($item) use ($supplierTypeId)
{
return $item->supplier_type_id == $supplierTypeId;
});