Basic Usage Of Cache In Laravel 7

In this tutorial we're going to look at the basic usage of the Laravel cache. The use of Laravel cache , its makes our site more faster than only use of query builder. In this tutorial we will see how we can implement laravel cache mechanism in our application. 

Laravel makes it easy for us to switch out how we want caching to be generated. It is extremely easy for us to switch out the drivers. Just check out config/cache.php to see the available drivers which are. In this lecture we will use redis to complete our laravel cache example. For this you have to setup redis in your environment. 

In this laravel cache tutorial i will explain how to use laravel cache and why we will use and when to use laravel cache. You will also learn laravel cache best practices from this laravel basic cache tutorial.


Caching in Laravel 

So let's start our tutorial for Laravel Caching. 

Step 1:  Create Model , Factory & Controller 

To complete this tutorial we need model , factory for quick data insert and controller for retrieve our caching data. 

php artisan make:model Post -fmr


After running this command , Post model, PostFactory and PostController will be generated. 


Step 2: Setup Post Table

Now we have to add some fields for our posts table. 


    public function up()
        Schema::create('posts', function (Blueprint $table) {


Step 3: Setup Post Factory 

Now we have to setup our post factory to insert dummy data. 


use App\Post;
use Faker\Generator as Faker;

$factory->define(Post::class, function (Faker $faker) {
    return [
       'user_id' => function(){
        	          return \App\User::all()->random();
       'category_id' => function(){
         	          return \App\Category::all()->random();
       'title' => $faker->sentence(5),
       'body' => $faker->text


Step 4: Setup database

Now you have to setup your database to run migrate command. So after setup database and after creating migrate , now just we have to add some dummy data. 


Step 5: Add dummy data

Now open your command line interface and paste this command to your command prompt.

1. php artisan tinker
2. factory(\App\Post::class,1000)->create()
3. exit


After running this command , one thousand post would be created. Now we will use file as our cache driver. You can use redis.


Read more : Laravel 6 Authentication Example From Scratch

Now this time we have to create event and listener. We will create event and listener cause we will fetch data from laravel cache, if data not exists in cache then we will fetch from database. If some new data creates then we just trigger a listener to add these new data to our cache. Hope you will understand.

Step 6: Make Event and Listener

Run following command to make event and listener.

php artisan make:event PostCreated
php artisan make:listener PostCacheListener


now open PostCreated.php


namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class PostCreated
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public function __construct()

    public function broadcastOn()
        return [];



namespace App\Listeners;

use App\Post;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use cache;

class PostCacheListener
    public function __construct()

    public function handle($event)
        cache()->forget('posts'); //forget all the cache data initially 

        $post = Post::all(); //fetch all data

        cache()->forever('posts', $post); // and put them into cache forever


Here first when event is fired then we will remove all the cache data. After then we will fetch all the data from dabase and put them into laravel cache forever. You can put them for couple of minutes , day, year whatever you want. 

Now open your app\Post.php model and those line of codes.


namespace App;

use App\Events\PostCreated;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
  protected $guarded = [];

  protected $dates = [

  protected $dispatchesEvents = [
    'created' => PostCreated::class //When a post is created then this Event will be fired


Step 7: Register Event and Listener

Now time to register our event listener. Cause we have to tell laravel that hey laravel now we are going to load a event listener, you load it. 


namespace App\Providers;

use App\Events\PostCreated;
use App\Listeners\PostCacheListener;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;

class EventServiceProvider extends ServiceProvider
    protected $listen = [

        PostCreated::class => [


    public function boot()



Step 8: Setup Post Controller

Now finally open your PostController and paste this following code.


namespace App\Http\Controllers\Frontend;

use cache;
use App\Http\Controllers\Controller;
use App\Post;
use Illuminate\Http\Request;

class FrontendController extends Controller
    public function Index()
        $data['posts'] = cache('posts', function () {
            return Post::with('user', 'category')->orderBy('created_at', 'desc')->take(5)->get();

        return view('welcome', $data);


Here first we have checked that if already data exists in cache or not, if not then we call a callback function and fetch data from database.


Read also : How to Use Laravel Cache For Quick Load Time


So now if we load our page , all the data will come from cache. If a new content is created then only this new content query will be load in our site, not the all content.

Hope you will enjoy this laravel cache tutorial and now you know how to use Laravel cache and why we use Laravel cache in our application. 


#laravel-6 #laravel #events #listeners #laravel-cache #cache