Caching Eloquent model instances with Redis
<p>So in Laravel 5.1, I have two Eloquent Models:</p>

<pre><code>\App\Model\Product
\App\Model\Brand
</code></pre>

<p>There is a one-to-many relationship between Brand and Product (i.e. one Brand may have many Products). In our system, every time we want to retrieve an eloquent model of a product, we eager load the brand, as such:</p>

<pre><code>$product = \App\Model\Product::whereId({integer})-&gt;with('brand')-&gt;first();
</code></pre>

<p>We do not expect the products to change very often, so in order reduce database queries and improve performance, we want to cache these Product models with Redis, so that before we perform the database query, we would check if the Product instance is already stored in the cache. So my question is, what would be the best approach for being able to store and retrieve these product instances from Redis?</p>

<p>I know that we can convert an eloquent model to JSON by doing:</p>

<pre><code>$json = $product-&gt;toJson();
</code></pre>

<p>That would technically allow me to store the "stringified" model in Redis. However, how would I be able to do the oposite - convert a stored JSON back into a Product instance (with the eager loaded Brand relation in place as well) that is available for me to use in code as a normal model instance?</p>

<p>Furthermore, in order to reduce Redis operations, this would have to work with MGET, allowing me to retrieve many instances at once. Pipelining get operations is also acceptable.</p>

<p>Is this doable, or, is there a better approach to accomplishing this?</p>

<p>Thank you in advance.</p>