Using Cache in Laravel

Created At: 2021-10-26 17:05:43 Updated At: 2021-10-28 02:28:30

When to use Cache

Caching is a great way to optimize your website resources like bandwith and speed. Once you cache your laravel blade files or resources, next time someone hits the route or visit the page, Laravel will get the content from cache.

Caching allows us to avoid expensive operations. Using Caching we can save the predefined result in memory.

 

Creating Cache

To use or create cache, you can simply call 

cache()->remember("myId", time, function(){});

So remember function takes an id. It could any unique ID. The ID could be even a slug . Then you memtion the caching time, meaning how long it should persist. This time could be seconds, minutes, days, years or forever.

if(!file_exists($path)){
  return redirect('/');
}
cache()->remember("posts.{$slug}", 5, function() use($path){
  return  file_get_contents($path);
}

The above remember function will remember the given file for 5 seconds. In the above function we passed the path so that, laravel knows where to find it.

So the final version would be 

if(!file_exists($path)){
  return redirect('/');
}
$post = cache()->remember("posts.{$slug}", 5, function() use($path){
  return  file_get_contents($path);
}

return view('post', [ 'post'=>$post]);

And withing the fucntion you mention your file name and do additional logic.

 

Add Time

For caching time, you can use addtional helper function like 

now()->addMinutes(20)
now()->addDays(20)

So the first line would add the cache for 20 minutes and second line would cache for 20 days.

 

Cache with Query

You can directly return Cache::remember from using Facades. You can cache your queries. See the example below.

return Cache::remember('en.tests', 60, function() {
        $teachers = EnArticle::where(['type_id'=>2])->orderBy('updated_at','asc')->get();
       //$teachers = $article->getTeachers();

        $courses = new EnCourse();
        $courses = $courses->getAll();
        $join = EnArticle::where(['type_id'=>3])->orderBy('created_at', 'asc')->get();
        return view('en.index',['teachers'=>$teachers, 'courses'=>$courses, 'join'=>$join, 'active'=>1])->render();
});

As you can see, we are doing queries using our Eloquent model. and you should return Cache::remember from your controller.

We used the forget function from the Cache Facades to forget our cache using the ID. See another example using query and eloquent model

$result = Cache::remember('users', $seconds, function () { 
    return DB::table('users')->get(); // By Using DB. 
});

You can connect to any database table and return the data from there.

$result = Cache::remember('users', $seconds, function () {
    return User::get();   // By Using Eloquent
});

 

Forgetting Cache

Here 'en.tests' is an ID for this cache. Of course you can forget your cache like below

Cache::forget('en.tests');

You can flush all the cache data from the memory. It will remove cache data for all the ID's

Cache::flush();

Comment

Add Reviews