Laravel error-safe methods

A few small, yet powerful methods for writing error-safe logic, similar to the native PHP null-safe operator used for strings. Although a sharp knife, it can be useful in a few situations.

Laravel1 / 3Level:

optional()

Imagine you're not sure if a certain method will work in every situation. To demonstrate this, let's use the following example:

return $post->date->format('d-m-Y');

Now I can hear you thinking "Applying ?-> also prevents us from getting an error.". Unfortunately, not so much.

return $post->date?->format('d-m-Y');

Although this may feel like a logical solution, this will in fact give us an error in the case $post->date is a string, instead of a Carbon instance. This makes sense when you think about it. We're telling PHP to perform our format method on a piece of string, which is not tolerated. Nor should it be.

The "null safe operator" was introduced by PHP to prevent further method chaining in case the prior value is NULL. In our case it is a string, which means it will get ignored completely.

Now let's suppose it's not absolutely critical for this date to be displayed. Although data accuracy is important, there may also be cases where avoiding errors is even more important. And, for the sake of argument, we're not able to find any other solution. In those situations the optional helper as provided by Laravel will certainly come in handy.

return optional($post->date)->format('d-m-Y');

By the way, it's quite interesting to see how the optional helper works behind the scenes.

Anyway, while this certainly doesn't solve the underlying issue, which is to whether or not we are dealing with dates or strings, it can certainly prevent errors from occurring and disrupting UX. Again, this may be a sharp knife, so use it with caution.

rescue()

You're probably familiar with the try { } catch { } blocks to handle exceptions using custom logic. Personally though, I find this whole closure to be kind of long and dreadful in some occassions. Laravel has a nice way to deal with this. Imagine the following, traditional way of catching an error:

try {
    $response = my_quirky_function();
} catch (\Exception $e) {
    $response = 'My fallback value.';
}

Now let's see how the rescue() helper would handle this:

$response = rescue(fn() => my_quirky_function(), 'My fallback value.');

While some may argue that the try { } catch method is far more readable, I can also imagine others who like the shorter version.

By the way, there's a third argument to the rescue function, whether or not to report the error to logs and whatever. It's turned on by default, but you could turn this off if you're afraid of getting flooded with error notifications.

Conclusion

Although some would advice against suppressing errors at all, I do think there are times when they may come in helpful. However, knowing when and where to use them is entirely up to you. But you strike me as the kind of person who knows what you're doing.