Laravel Tip: How to avoid error when no relation exists

Laravel is the most famous PHP framework and it is used widely.

As a Laravel Developer you must have used Eloquent and Eager/Lazy loading to reduce the query time and for optimization.

Sometimes you try to call a relationship that does not exist and boom your system crashes.

Let suppose we have an article and category Models and they are mapped using association.

If an article is not associated with a category, then this code will throw an error. To be on the safe side use PHP 8.0 Null-safe operator. This allows us to optionally chain as many times as possible. We could also do $article->category?->creator?->name and it will still not throw an error. If there is no category or creator, it will just return null

laraveltip.jpg

Now, you don't need to worry about the relation exists or not the Null-safe operator will take care of that for you.

Hope this helps.