Laravel: Caching your Query with only one method

Behold! The power of… macros!

public function (Request $request)
{
$request->validate([
'email' => 'required|unique:users',
]);
// ...
}
$votes = 100;$users = Cache::remember('users', 60, function () use ($votes) {
return Users::has('comments')
->where('votes', '>', $votes)
->get();
});

The Plan, The Class and the Macro

$results = User::where('something')->remember(60)->get();
Image for post
Image for post
$votes = 100;$users = Cache::remember('users', 60, function () use ($votes) {
return Users::has('comments')
->where('votes', '>', $votes)
->get();
});
$users = Users::has('comments')->where('votes', '>', $votes)
->remember()
->get();

Graphic Designer graduate. Full Stack Web Developer. Retired Tech & Gaming Editor.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store