Basic Usage of Cache in Laravel

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. 

laravel-caching-example

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. 

database\migrations\posts.php

    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedInteger('user_id');
            $table->unsignedInteger('category_id');
            $table->string('title');
            $table->longText('body');
            $table->string('thumbnail_path')->nullable();
            $table->timestamps();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
        });
    }

Step 3: Setup Post Factory 

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

database\factoryies\PostFactory.php

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. 

Step 6: Setup cache.php file

Open config\cache.php and replace CACHE_DRIVER  file to redis.

'default' => env('CACHE_DRIVER', 'redis'),

and .env file also have to be changed with redis.

CACHE_DRIVER=redis

Step 7: Setup predis

Run this following command 

composer require predis/predis

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 8: 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

app\Events\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 [];
    }
}

app\Listeners\PostCacheListener.php

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.

app\Post.php

namespace App;

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

class Post extends Model
{
  protected $guarded = [];

  protected $dates = [
    'created_at'
  ];

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

Step 9: 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. 

app\Providers\EventServiceProvider.php

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 => [
            PostCacheListener::class,
        ],

    ];

    public function boot()
    {
        parent::boot();

        //
    }
}

Step 10: Setup Post Controller

Now finally open your PostController and paste this following code.

app\Http\Controllers\PostController.php

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.

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. 

Codechief is a very fast growing community among programmers and have a reach of around 1 million+ readers globally. Contribution at Codechief is open for all those who have a passion to learn and help others by sharing their knowledge. If you think you have the zeal to learn, start contributing on Codechief contribute. you can also mail your article to [email protected] See your article appearing on the codechief main page and help other code.

We believe that everyone has the right to learn, so we allow both students and professionals to contribute on Codechief.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

A web enthusiastic, self-motivated Full-Stack Web Developer from Dhaka, Bangladesh with experience in developing applications using JavaScript, Laravel & Wordpress specifically. Facebook Github Website