How to use the ?? ‘ ‘ operator in Laravel

The ?? ” operator is the Ternary Operator in PHP Laravel. We can use it in Laravel Blade and Controller files for variables that have null or undefined values. Let us see how we can use the ?? ‘ ‘ operator in Laravel.

It is useful when we return a value from controller to create some custom view or use it for some other purpose. We can add to it a condition followed by a question marks (??). Then comes the expression that will execute if the condition is true along with a colon (:). In the end, add the expression that will execute if the condition is false or the variable un available.

The code snippet shows how we to make use of the ternary operator and isset keyword in conditional statements.

// Null Coalesce Operator in PHP (Laravel) - $statement ?? ''
$bookName = $book->name ?? 'Not Available';

// The above Statement is identical to this if/else statement
if (isset($book->name)) {
    $bookName  = $book->name;
} else {
    $bookName = 'Not Available';
}

The second code snippet works as an explanation of how the ternary operator works. It checks if the $book->name is set using the isset keyword. isset will return true, if the variable has a value or is set with a specific value. So, if the book name is set, the expression inside if block assigns it to the $bookName variable, otherwise it sets it as ‘Not Available’

Notice how the ?? ‘ ‘ operator makes a complex five line code compact in a single line with minimal work and space. This makes it relatively easy to use multiple conditional statements. Consider having a large JSON file of records, whose versions will update with time, adding new fields or changing field names. In such files if we refer to a specific field, and it is not present, we might get errors. Ternary operator catches these error very well.

How the ?? ‘ ‘ operator handles errors

The ternary operator helps avoid errors when a variable which is empty and not assigned a value needs to be accessed. It works to catch the exception when you may add a new property in the book object. For example $book->authorNo, but it is not present in previous records. Now whenever you edit an old record, you might get errors like index not defined or undefined variable.

Using the isset or ternary operator conditions. helps handle this error very well. It makes the application work smoothly without any error. When an object property is not available, ternary operator is useful. It passes it under the condition defined and sets it as “” (null) or any defined default value.

Leave a Comment