DEV Community

trungpv
trungpv

Posted on

Laravel: Why I Love Cache:remember(‘me’, fn () => ‘I Love Laravel’);

Today I want to share you guys about the feature that I feel impress the most when I develop the Laravel app.

After few years, I think Redis is the important part I must use for every Laravel projects that I start.

Why? The Redis is very useful like: Caching, Queue… I can not name which parts or services use it. Help me comments If you know.

Talk about the use case, It easy for you guys can imagination

Today, I have an issue to improve the Laravel Sanctum that I use to authenticate the API. But the table personal_access_tokens read and write too much. So, I think it worthless in the app. You can read detail here[https://dylanbaine.com/read/scaling-laravel-sanctum]. I only show you why I love Cache:remember

Instead of make the query for every request, We can use the Cache to reduce stress on the server. I think you can not see it for the small app. But for the large app and especially when you use the AWS Lambda which cost how much you use it. It save your money :)

Example:

// Before

return static::where('token', hash('sha256', $token))->first();

// After

return Cache::remember("PersonalAccessToken::$token", 600, function () use ($token) {
    return parent::findToken($token) ?? '_null_';
});
Enter fullscreen mode Exit fullscreen mode

An other use case, When you make the dashboard and counting the numbers.
But every time you access the page, It will make a query. So, for example you make a count query with the table have 30 mils records. I think it will cost few seconds and I think you do not need it in the real-time.

// Before
$usersCount = User::count();

// After
$usersCount = Cache::remember('usersCount', $seconds, function () {
    return User::count();
});
Enter fullscreen mode Exit fullscreen mode

Anyway, You must read this page in the Laravel document: [https://laravel.com/docs/9.x/cache#retrieve-store]

Top comments (0)