salep
salep

Reputation: 1380

Laravel 5.1 Redis cache

I'm trying to implement a very basic caching mechanism into my Laravel app.

I installed Redis, started it via terminal (src/redis-server) and changed cache from file to redis in Laravel's config file, but it takes LONGER (1s vs 2s) than regular query when I use cache.

Am I missing something here? I just want to cache a query for 10 minutes.

Here's my FeedController.php

namespace App\Http\Controllers\Frontend\Feed;

use Illuminate\Http\Request;
use Auth;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Models\Company;
use Redis;
use Cache;


class FeedController extends Controller
{

    public function index()
    {

        if (Cache::has('companies')) {
            // cache exists.
            $companies = Cache::get("companies");
        } else {
            // cache doesn't exist, create a new one
            $companies = Cache::remember("companies",10, function() {
                return Company::all();
            });

            Cache::put("companies", $companies, 10);
        }


        return view('index')->with('companies', $companies)
    }

My view

@foreach($companies as $company)
    {{$company->name}}
@endforeach

Upvotes: 0

Views: 1425

Answers (1)

Tijs van Erp
Tijs van Erp

Reputation: 36

First of all, caching isn't always faster. Second, you're double checking the cache.

You can just use:

$companies = Cache::remember("companies",10, function() {
            return Company::all();
        });

It checks of the cache item exist, and if not it will execute the closure and cache the result in the specified key. The cache:has if/else is unnecessary and will only slow it down.

Upvotes: 2

Related Questions