Laravel Framework, PHP & MySQL, Tutorials

How Laravel's optional() helper can keep your pages running

If you've ever used Laravel ORM to create a relationship between tables you will have come across the following problem at some point. Let's say you have a posts table and a users table.

When displaying posts you would show the user who created the post something like:

{{ $post->user->name }}

That's assuming there has been a user() method defined within the post model.

Now if a user was deleted or was missing from the post table you would get an exception when viewing the page. Far from ideal. If only there was a way for silently fail and let the page carry on displaying.

Thankfully there is! the optional() helper. This helper can be wrapped around the relationship call and will fail silently if there is an error otherwise the relationship will show as expected.

{{ optional($post->user)->name }}

Notice the column being displayed is after the closing parenthesis.

This only that in place you have the piece of mind the page will show even if one of your relationships fail.

David Carr

David Carr

For the past 12 years, I’ve been developing applications for the web using mostly PHP. I do this for a living and love what I do as every day there is something new and exciting to learn.

In my spare time, the web development community is a big part of my life. Whether managing online programming groups and blogs or attending a conference, I find keeping involved helps me stay up to date. This is also my chance to give back to the community that helped me get started, a place I am proud to be apart of.

Besides programming I love spending time with friends and family and can often be found together going out catching the latest movie, staying in playing games on the sofa or planning a trip to someplace I’ve never been before.