Laravel Cache Remember Forever if Truthy

I kept needing a cache method that would only store a value permanently if the result was truthy. For expensive operations that might return null or false, I wanted to keep trying until I got a real result, then cache that forever. The problem Laravel’s Cache::rememberForever() caches any result, including null/false values. Fairly often I want to cache successful results and keep retrying failed ones. The solution Add this macro to your AppServiceProvider boot method: ...

June 19, 2025 · 2 min

Assigning variable defaults in PHP

It’d be nice if PHP had a quick Or-Equals expression like Ruby: user ||= User.new but we make do with few slightly less sugary idioms. The standard way if (isset($user)) { $user = new User(); } A bit shorter $user = isset($user) ? $user : new User(); Shorter still This is my preferred way of making sure variables are set. Short and clear. isset($user) || $user = new User(); Expressions with defaults It’s usually best not to treat variable assignments as booleans but in cases like this I think it’s clear enough what’s happening. ...

July 16, 2013 · 1 min · Paul