Many people do it differently, but when best practice is troubling, I find the best place to cache is in your repository.
Your controller should not know too much about the data source, I mean, whether it comes from the cache or comes from the database.
Caching in the controller does not support the DRY (Do not Repeat Yourself) approach, because you duplicate your code in several controllers and methods, thereby complicating their execution.
So, for me, this is the way I download in Laravel 5, not as much if using laravel 4:
//1. Create GalleryEloquentRepository.php in App / Repositories
<?php namespace App\Repositories; use App\Models\Gallery; use \Cache; class GalleryEloquentRepository implements GalleryRepositoryInterface { public function all() { return Cache::remember('gallerys', $minutes='60', function() { return Gallery::all(); }); } public function find($id) { return Cache::remember("gallerys.{$id}", $minutes='60', function() use($id) { if(Cache::has('gallerys')) return Cache::has('gallerys')->find($id);
// 2. Create GalleryRepositoryInterface.php in App / Repositories
<?php namespace App\Repositories; interface GalleryRepositoryInterface { public function find($id); public function all(); }
// 3. Create RepositoryServiceProvider.php in application / providers
<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; class RepositoryServiceProvider extends ServiceProvider {
//4. On the controller you can do it
<?php namespace App\Http\Controllers; use \View; use App\Repositories\GalleryRepositoryInterface; class GalleryController extends Controller { public function __construct(GalleryRepositoryInterface $galleryInterface) { $this->galleryInterface = $galleryInterface; } public function index() { $gallery = $this->galleryInterface->all(); return $gallery ? Response::json($gallery->toArray()) : Response::json($gallery,500); } }