You may have cached model data before, but I'm going to show you a more elaborate Laravel model caching technique using dynamic logging models, which I started with RailsCasts learned techniques.
Using the model's unique cache key, you can cache properties and associations on the model that automatically update (and cache invalidate) when the model (or associated model) is updated. One benefit is that accessing cached data is faster than in the controller. The data cached in is more reusable because it's on the model rather than in a single controller method.
This is the key point of this technology:
Suppose you have many Comment Article models, given the following Laravel blade template, you can access the /article/:id route like the following When you get the count of comments:
<h3 id="article-comments-count-nbsp-nbsp-str-plural-Comment-nbsp-article-comments-count">$article->comments->count() {{ str_plural('Comment', $article->comments->count())</h3>
You can cache the count of comments in the controller, but when you have multiple one-time queries and data that need to be cached, the controller can become very bloated and ugly. Using controllers, accessing cached data is also not very convenient.
We can build a template that only accesses the database when the article is updated, and all code that accesses the model can get the cached value:
<h3 id="article-cached-comments-count-nbsp-nbsp-str-plural-Comment-nbsp-article-cached-comments-count">$article->cached_comments_count {{ str_plural('Comment', $article->cached_comments_count)</h3>
By using the model accessor, we can cache Comment count based on the last article update.
So, how should we update the updated_at column value of the article when comments are added or deleted?
Enter the touch method first to see.
Triggering of the model
You can update the updated_at column value of the article by using the touch() method of the model:
$ php artisan tinker
>>> $article = \App\Article::first(); => App\Article {#746 id: 1, title: "Hello World", body: "The Body", created_at: "2018-01-11 05:16:51", updated_at: "2018-01-11 05:51:07", } >>> $article->updated_at->timestamp => 1515649867 >>> $article->touch(); => true >>> $article->updated_at->timestamp => 1515650910
We can invalidate the cache with an updated timestamp value. But when adding or deleting a comment, how do we trigger the modification of the updated_at field of the article?
It happens that there is a property in the Eloquent model called $touches. Here is what our comment model looks like:
<?php namespace App; use App\Article; use Illuminate\Database\Eloquent\Model; class Comment extends Model { protected $guarded = []; protected $touches = ['article']; public function article() { return $this->belongsTo(Article::class); } }
The $touches property here is an array that contains the associated information that will cause "triggers" when the comment is created, saved, and deleted.
Cached properties
Let’s go back to the $article->cached_comments_count accessor. The implementation of this method might look like this in the App\Article model:
public function getCachedCommentsCountAttribute() { return Cache::remember($this->cacheKey() . ':comments_count', 15, function () { return $this->comments->count(); }); }
We cache the model for 15 minutes using the cacheKey() method of the unique key value, and then simply return the comment count value in the closure method.
Note that we also use the Cache::rememberForever() method to delete expired key values relying on the garbage collection strategy of the cache mechanism. I set up a timer so that during the cache refresh interval of every 15 minutes, the cache would have the highest hit rate for most of that time.
The cacheKey() method needs to use the unique key value of the model, and the corresponding cache will be invalidated when the model is updated. The following is my cacheKey implementation code:
public function cacheKey() { return sprintf( "%s/%s-%s", $this->getTable(), $this->getKey(), $this->updated_at->timestamp ); }
The model's cacheKey() method example output result may return the following string information:
articles/1-1515650910
This key value is composed of the table name and model id value and the timestamp value of the current updated_at. Once we trigger this model, the timestamp value will be updated and our model cache will be invalidated accordingly.
Here is the complete code for the Article model:
<?php namespace App; use App\Comment; use Illuminate\Support\Facades\Cache; use Illuminate\Database\Eloquent\Model; class Article extends Model { public function cacheKey() { return sprintf( "%s/%s-%s", $this->getTable(), $this->getKey(), $this->updated_at->timestamp ); } public function comments() { return $this->hasMany(Comment::class); } public function getCachedCommentsCountAttribute() { return Cache::remember($this->cacheKey() . ':comments_count', 15, function () { return $this->comments->count(); }); } }
Then the associated Comment model:
<?php namespace App; use App\Article; use Illuminate\Database\Eloquent\Model; class Comment extends Model { protected $guarded = []; protected $touches = ['article']; public function article() { return $this->belongsTo(Article::class); } }
What next?
I've shown you how to cache a simple comment count, but what about caching all comments?
public function getCachedCommentsAttribute() { return Cache::remember($this->cacheKey() . ':comments', 15, function () { return $this->comments; }); }
You can also choose to convert the comments to an array instead of serializing the model, allowing only simple array access to the data on the front end:
public function getCachedCommentsAttribute() { return Cache::remember($this->cacheKey() . ':comments', 15, function () { return $this->comments->toArray(); }); }
Finally, I defined the cacheKey in the Article model () method, but you may want to define this method via a trait called ProvidesModelCacheKey so that you can use it in a composite model or define the method for all model extensions in a base model. You might even want to use a contract (interface) for your model that implements the cacheKey() method.
Recommended tutorials: "PHP Tutorial" "Laravel"
The above is the detailed content of How to cache data at the Model layer in Laravel?. For more information, please follow other related articles on the PHP Chinese website!

Laravel's core functions in back-end development include routing system, EloquentORM, migration function, cache system and queue system. 1. The routing system simplifies URL mapping and improves code organization and maintenance. 2.EloquentORM provides object-oriented data operations to improve development efficiency. 3. The migration function manages the database structure through version control to ensure consistency. 4. The cache system reduces database queries and improves response speed. 5. The queue system effectively processes large-scale data, avoid blocking user requests, and improve overall performance.

Laravel performs strongly in back-end development, simplifying database operations through EloquentORM, controllers and service classes handle business logic, and providing queues, events and other functions. 1) EloquentORM maps database tables through the model to simplify query. 2) Business logic is processed in controllers and service classes to improve modularity and maintainability. 3) Other functions such as queue systems help to handle complex needs.

The Laravel development project was chosen because of its flexibility and power to suit the needs of different sizes and complexities. Laravel provides routing system, EloquentORM, Artisan command line and other functions, supporting the development of from simple blogs to complex enterprise-level systems.

The comparison between Laravel and Python in the development environment and ecosystem is as follows: 1. The development environment of Laravel is simple, only PHP and Composer are required. It provides a rich range of extension packages such as LaravelForge, but the extension package maintenance may not be timely. 2. The development environment of Python is also simple, only Python and pip are required. The ecosystem is huge and covers multiple fields, but version and dependency management may be complex.

How does Laravel play a role in backend logic? It simplifies and enhances backend development through routing systems, EloquentORM, authentication and authorization, event and listeners, and performance optimization. 1. The routing system allows the definition of URL structure and request processing logic. 2.EloquentORM simplifies database interaction. 3. The authentication and authorization system is convenient for user management. 4. The event and listener implement loosely coupled code structure. 5. Performance optimization improves application efficiency through caching and queueing.

Laravel's popularity includes its simplified development process, providing a pleasant development environment, and rich features. 1) It absorbs the design philosophy of RubyonRails, combining the flexibility of PHP. 2) Provide tools such as EloquentORM, Blade template engine, etc. to improve development efficiency. 3) Its MVC architecture and dependency injection mechanism make the code more modular and testable. 4) Provides powerful debugging tools and performance optimization methods such as caching systems and best practices.

Both Django and Laravel are full-stack frameworks. Django is suitable for Python developers and complex business logic, while Laravel is suitable for PHP developers and elegant syntax. 1.Django is based on Python and follows the "battery-complete" philosophy, suitable for rapid development and high concurrency. 2.Laravel is based on PHP, emphasizing the developer experience, and is suitable for small to medium-sized projects.

PHP and Laravel are not directly comparable, because Laravel is a PHP-based framework. 1.PHP is suitable for small projects or rapid prototyping because it is simple and direct. 2. Laravel is suitable for large projects or efficient development because it provides rich functions and tools, but has a steep learning curve and may not be as good as pure PHP.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft