laravel-advanced-1-laravel-cache-and-observer-61195a2f73a221629051439.jpg

Laravel Advanced - #1 Laravel Cache and Observer

Laravel

Subhadip Ghorui

2 years ago

Subhadip Ghorui

      In this post, we are going to talk about how to use Laravel cache in Laravel 8. We will learn about php cache and observer in Laravel.

 

Watch Video:

 

 

Start with a fresh project

 

1. Create a fresh Laravel project

composer create-project laravel/laravel laravel-advanced
cd laravel-advanced

edit the .env file and put database credentials. In this tutorial, we will use the SQLite database.

DB_CONNECTION=sqlite

2. Create database.sqlite file in database folder and run

php artisan migrate

 

Install telescope to watch the API calls and database queries

 

    Telescope makes a wonderful companion to your local Laravel development environment. Telescope provides insight into the requests coming into your application, exceptions, log entries, database queries, queued jobs, mail, notifications, cache operations, scheduled tasks, variable dumps, and more.

composer require laravel/telescope
php artisan telescope:install
php artisan migrate

Go to localhost:8000/telescope to view the dashboard.

 

Make some Data

 

We will create some posts for this tutorial.

1. Create Post model with migration and controller

php artisan make:model Post -mc

2. In app/Models/Post.php enable mass assignable.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;
    // protected $guarded = [];
    protected $fillable = ['title', 'body'];
}

3. In app/Http/Controllers/PostController.php we create some methods for our posts data.

<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class PostController extends Controller
{
    public function index(){
        $posts = Post::all()

        return response($posts,200);
    }
    public function store(Request $request){
        $post = Post::create($request->all());
        return response($post,200);
    }
}

4. In routes/api.php define routes.

<?php

use App\Http\Controllers\PostController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;


Route::get('/posts', [PostController::class, 'index']);
Route::post('/post', [PostController::class, 'store']);

5. To get all posts as json goto - /api/posts and to create a new post use postman and enter post title and body.

postman-create-post

 

What is PHP cache?

 

Normally when we request the data from the server, the server query the data from the database. But if the data is not changing too much often, the database's query slows your application and the server runs out of memory when handling huge http requests. Here comes the cache. The server cache the database queries so that when the user requests the same data from the server, the server did not query the database rather than return the data it already queried and store as cache in the database.  

In laravel, we set up a key to store the data from the database. Cache::remember() will get the data from the cache, if not found query from database and store in key value in the cache. We need also a expiration time so that it will destroy after that time and query the database for latest data.

In app/Http/Controllers/PostController.php we will cache the posts.

<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class PostController extends Controller
{
    public function index(){
        $posts = Cache::remember('posts', 60*60, function () {
            return Post::all();
        });

        return response($posts,200);
    }

}

But what the data table is modified. If you create a new dataset will not view the newly created data on the posts page. This is happening because laravel does not know if the data is updated or not. It will not query the data from the database again until the time is expired.

What is the solution then ??

 

Laravel Observer

 

Here comes the observer. As you can understand its name, it observes the data table if it changes or not.

1. Create an observer for the Post model

php artisan make:observer PostObserver --model=Post

Observer classes have method names that reflect the Eloquent events you wish to listen for. Each of these methods receives the affected model as their only argument.

2. We will user created method now. We will clear the cache of the post if a new post is created.

app/Observer/PostObserver.php

<?php

namespace App\Observers;

use App\Models\Post;
use Illuminate\Support\Facades\Cache;

class PostObserver
{
    /**
     * Handle the Post "created" event.
     *
     * @param  \App\Models\Post  $post
     * @return void
     */
    public function created(Post $post)
    {
        Cache::forget('posts');
    }

    /**
     * Handle the Post "updated" event.
     *
     * @param  \App\Models\Post  $post
     * @return void
     */
    public function updated(Post $post)
    {
        Cache::forget('posts');
    }

    /**
     * Handle the Post "deleted" event.
     *
     * @param  \App\Models\Post  $post
     * @return void
     */
    public function deleted(Post $post)
    {
        Cache::forget('posts');
    }

    /**
     * Handle the Post "restored" event.
     *
     * @param  \App\Models\Post  $post
     * @return void
     */
    public function restored(Post $post)
    {
        Cache::forget('posts');
    }

    /**
     * Handle the Post "force deleted" event.
     *
     * @param  \App\Models\Post  $post
     * @return void
     */
    public function forceDeleted(Post $post)
    {
        Cache::forget('posts');
    }
}

3. Register in app/Providers/AppServiceProvider.php.

<?php

namespace App\Providers;

use App\Models\Post;
use App\Observers\PostObserver;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Post::observe(PostObserver::class);
    }
}

4. Now If we create a new post the Posts page will be updated and a new post will be available.

 

Github

⭐Github repo: https://github.com/subhadipghorui/laravel-advanced-topics

Please Like and share this with your friends.

0 people like this
1707 views
0 comments
Share it on your social media account.

Please Sign in to post comments - Sing in or Register

0 Comments