Defensive Programming | Laravel find()

Defensive Programming

One of the things I’ve learned in my career is to code defensively.

Laravel makes it very easy to ask for an object, but it also makes it very easy to get it wrong. If you request an object using the find method and it doesn’t find it, you don’t get an error. You get a null. If you then request a property on that object, without first checking for a null, you will get a run-time error.

This is pretty basic stuff, but it never hurts to go over it again.

Wrong:

 

Right:

 

The first block will throw an error if Widget #23 doesn’t exist in the database. The second checks for it’s existence and then only reaches for the name if it found it.

 

 

Are you also a PHP programmer? I’ve got other blog entries that you might be interested in!

 

More about me

I have been programming for almost 20 years. It all started with Basic and RPG III way back in high school, and have played around with many languages. PHP and Swift my my main languages today.

Some sites I have built:

For fans of BMX legend Scotty Cranmer: https://ScottyFan.com

Meet my Basenji’s Graham and Ginger: https://BarooBoos.com

Meet my newest Basenji, Zulu: https://ZuluJoy.com