Join 25,000+ Laravel Developers and join the free Laravel Newsletter
Update Your Blade Templates to Use the Null Coalesce Operator
Laravel Tutorials / updated: August 10, 2018

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.

This appeared first on Laravel News
Laravel News Partners

Newsletter

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