Stricter is better

Stricter is better
Photo by Andrew Seaman / Unsplash

Laravel updates all the time. I run a composer update when I start writing any kind of code. I can count the number of breaking changes I've encountered on one hand, maybe on one finger. A recent update to Laravel a couple months ago introduced an easy way to enable Eloquent's strict mode.

  • No lazy loading
  • Exceptions when assigning non-fillable attributes
  • Exceptions accessing attributes that weren't retrieved or didn't exist

The second two bullets are less useful to me. For the second point, I normally run into it with a database exception when I'm updating an attribute I forgot to unguard. For the third, if you access an attribute that doesn't exist, the default behavior is for Laravel to return a null, not an error. But if you're building an interface and expecting that attribute you quickly notice when it isn't there.

The first bullet point is far more useful. Laravel likes to talk about things work "magically" (when you follow defined conventions, that is) but sometimes magic makes for a lazy programmer. Imagine if you tell your kids to come downstairs and as each one walks into the room, you tell them to go back upstairs and bring down dirty laundry from their room. That's lazy-loading in a nutshell. You should tell your kids to come downstairs and bring their laundry with them. In programming it's easy to do this by accident; often times you don't know you needed the laundry until the kids are already downstairs. But strict mode instead of letting you "lazily" load the need for the laundry forces you to go back and ask more efficiently.

What I'm listening to