Update Your Blade Templates to Use the Null Coalesce Operator

Update Your Blade Templates to Use the Null Coalesce Operator

In the next major release, Laravel 5.7 removes the Blade “or” Operator. Andrew Brown submitted a PR for Laravel 5.7 to Remove Blade Defaults from the framework, due to the new Null Coalesce operator available in PHP 7.

Although Laravel 5.7 is months away from release, it’s probably a good idea to preemptively replace “or” operator usage with PHP 7’s null coalesce operator.

PHP 7’s Null Coalesce Operator

The new null coalesce operator introduced in PHP 7 is an excellent addition to the PHP language that is extremely useful in your templates. It’s syntactic sugar for a frequent need of using the ternary operator with isset()

From the PHP manual, here’s a couple of examples of how it works:

<?php

// Fetches the value of $_GET['user'] and returns 'nobody'
// if it does not exist.
$username = $_GET['user'] ?? 'nobody';
// This is equivalent to:
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';

// Coalescing can be chained: this will return the first
// defined value out of $_GET['user'], $_POST['user'], and
// 'nobody'.
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';

You can even chain them, which is a bonus over the humble “or” operator that ships with Blade up to Laravel 5.6.

Here are a couple of more examples of how it works that might interest you using the excellent PsySH REPL:

$ psysh
>>> true ?? 'Is it true?'
=> true
>>> false ?? 'Is it false?'
=> false
>>> $person->getName() ?? 'Guest'
PHP Notice:  Undefined variable: person on line 1
>>> $person->name ?? 'Guest'
=> "Guest"

The Background of the Blade “or” Operator

Before the null coalescing operator, Blade handled the same problem with the “or” operator, which allows a default value when the first value isn’t set, separated by an “or”:

{{ $name or 'Guest' }}

Which is shorthand for:

isset($name) ? $name : 'Guest'

Laravel increased the PHP requirement to PHP 7 in Laravel 5.5, so in the previous version you could use the ?? operator if using PHP 7, but the framework needed to support PHP 5.

Update Now

Since Laravel 5.5 requires PHP 7, you can update your usage of the “or” operator to the null coalesce operator ahead of the Laravel 5.7 release later this year.


Filed in: Laravel Tutorials


Newsletter

Join the weekly newsletter and never miss out on new tips, tutorials, and more.

Laravel News Partners

Laravel Jobs

Web Application Developer
Independence, Ohio or Remote - US Based Only
Hurricane Labs
Graduate / Junior PHP Developer
Leamington Spa, Warwick
Synchro
Laravel Developer
Remote - US only
Pleio
Web Application Developer
Cleveland, OH
PS Lifestyle
Full-Stack Developer
Tampa, FL / Remote
Nu Image Medical
PHP Developer
Remote
X-Team
Full-Stack Developer
Sioux Falls, SD or Remote
Electric Pulp