How to set field caching in Laravel?

In Laravel, you can use caching to store field values in order to reduce database queries and improve performance. Here are the steps to set up field caching in Laravel.

  1. The database configuration file is named database.php.
  2. relationships
  3. mysql means “My Structured Query Language”
  4. postgresql
  5. Save the data.
'mysql' => [
    'driver' => 'mysql',
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', '3306'),
    'database' => env('DB_DATABASE', 'forge'),
    'username' => env('DB_USERNAME', 'forge'),
    'password' => env('DB_PASSWORD', ''),
    'unix_socket' => env('DB_SOCKET', ''),
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix' => '',
    'strict' => true,
    'engine' => null,
    'cache' => true,
],
  1. Don’t forget
  2. Individual using the system
use Illuminate\Support\Facades\Cache;

class User extends Model
{
    public function getNameAttribute()
    {
        return Cache::remember('user_name_' . $this->id, 60, function () {
            return $this->name;
        });
    }
}

The getNameAttribute method in the code above will retrieve the user’s name and store it in the cache. The key for the cache will be user_name_user id, and the cache will expire after 60 seconds.

  1. Finally, you can simply call the model’s fields directly where they are needed, for example:
$user = User::find(1);
echo $user->name;

By following the steps above, we can set field caching in Laravel to reduce the number of database queries and improve performance.

bannerAds