ItSolutionStuff.com

How to Store Data in Cache in Laravel?

By Hardik Savani β€’ November 5, 2023
Laravel

if you are work with large application which depend on large query and required large number of record at that time your application performence littel bit down. that problem overcome with laravel Cache functionality.

Laravel Cache provide to you store your large query in cache so your application performence improve.

first of all you must write "use Cache" keyword on top of the your class

Here is an example using Laravel’s Fluent Query Builder:

$users = DB::table('order')

->orderBy('price', 'desc')

->take(10)

->remember(60)

->get();

Of course, we can do the same thing using laravel Eloquent:

$users = Order::orderBy('price', 'desc')

->take(10)

->remember(60)

->get();

But, it's work fine with very simple database query

if you have work with more complex database query you need to use cache this way.

1.)Cache all records.

$orderTable = Cache::remember('orderTable', 60, function()

{

return DB::table('order')

->select(DB::raw(

"SOME COMPLEX JOINS ETC.."

))->get();

});

Here 'orderTable' is a cache variable you can use this when you get all records from the cache like that,

2.)Get records from Cache

$data = Cache::get('orderTable');

3.)remove Cache records from the Cache memory. it must be required when you insert new record other wise you want to update any records.

Cache::forget('orderTable');

I hope it can help you...

Tags: Laravel
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

πŸ“Ί Subscribe on YouTube

We Are Recommending You

β˜…

How to Add Custom Attribute in Laravel Model?

Read Now β†’
β˜…

Laravel - How to Upload Picture in Registration Form?

Read Now β†’
β˜…

Laravel Passwordless Login with Magic Link Tutorial

Read Now β†’
β˜…

Laravel Global Variable for All Views Example

Read Now β†’
β˜…

Laravel TCPDF: Generate HTML to PDF File Example

Read Now β†’
β˜…

How to set CC And BCC Email Address In Laravel Mail?

Read Now β†’
β˜…

Laravel Order By Multiple Columns Example

Read Now β†’
β˜…

How to Check Database Connection in Laravel?

Read Now β†’
β˜…

Laravel Send Scheduled Emails Tutorial

Read Now β†’
β˜…

Laravel Webcam Capture Image and Save from Camera Example

Read Now β†’
β˜…

How to Generate Random Unique String in Laravel?

Read Now β†’
β˜…

Laravel Select with Count Query with Group By Example

Read Now β†’