Laravel Advance | Install and Use Memcached

Raviya Technical
2 min readDec 21, 2021

In this tute, we will discuss how to use Memcached in laravel. I would like to share with you the laravel cache Memcached. it’s a simple example of a laravel cache driver Memcached. We will look at an example of laravel use Memcached. Follow bellow tutorial step of installing Memcached PHP laravel.

Laravel provides several drivers for caching your app with a database query, view, etc. here I will give you step-by-step instructions on how to install and use Memcached as a cache driver in the laravel application. you can easily use Memcached with laravel 6, laravel 7, and laravel 8 versions.

let’s see step by step configuration Memcached driver.

Install Memcached in Server

in this step we need to install Memcached in ubuntu server and PHP extension for it. so let’s run both commands

sudo apt-get install memcached

next you need to install the PHP extension for Memcached. it's version specify so it will install with your PHP version like "Sudo apt-get install php7.3-Memcached", sudo apt-get install php7.4-Memcached, etc. but for default, you can use as like bellow command:

sudo apt-get install php-memcached

Configure Memcached Driver:

now, we need to configure cache driver as Memcached on env file as like bellow:



you can see below the cache config file it will be as below:


<?phpuse Illuminate\Support\Str;return [....'stores' => [....'memcached' => ['driver' => 'memcached','persistent_id' => env('MEMCACHED_PERSISTENT_ID'),'sasl' => [env('MEMCACHED_USERNAME'),env('MEMCACHED_PASSWORD'),],'options' => [/* Memcached::OPT_CONNECT_TIMEOUT => 2000, */],'servers' => [['host' => env('MEMCACHED_HOST', ''),'port' => env('MEMCACHED_PORT', 11211),'weight' => 100,],],],]....]

Use Memcached Driver:

now, we will create a simple example route to cache our database records. let’s see bellow code:


Route::get('cache-data', function () {$user = \Cache::remember('user', 60, function() {return \App\Models\User::first();});});

Check Memcached Cache:

in this step, we will check Memcached driver cache is properly or not. you need to run the below command and get all keys cached:

php -r '$c = new Memcached(); $c->addServer("localhost", 11211); var_dump( $c->getAllKeys() );'

now you can use the key and get that content as below

telnet 11211get laravel_cache:user

now it will work great.

I hope it can help you…