The must have PHP ternary rescue helper

Sourav Rakshit
3 min readFeb 4, 2021
a cleaner alternative approach to ternary printing in php

Rendering stuffs conditionally is the most common job for programmers of any language and when it comes to PHP developers, the sight of html all mixed up with php logic is πŸ˜ͺ. .. (..you know)

πŸ₯½ If you are familiar with Vue or Alpine JS for handling class attribute value they use a neat syntax, which is something like this ___

conditionally rendering class name in Alpine JS

you pass in an object whose keys are class names, and values are boolean expressions to determine if those class names are applied or not

⚑ Here is how we’ll commonly do the equivalent in PHP β€” -

with blade syntax in Laravel

. . . and its dirty 😷

🎁 Here comes the tiny utility function to save our lives β€” -

utility: conditionally merge class names without using ternary operator

the concept is same, you pass an associative array where the key is the string to render & the value stands as boolean expression to resolve whether the string to be rendered / printed (for current example html class attribute value)

and use it as …

using utility to escape ternary operations for rendering class names

the readability is much better & looks neat 😍

πŸ’‘ Tip: If you use Laravel β€” -

we can create a string macro on Illuminate\Support\Str helper class to make things tidy, here is how :-

in app/Providers/AppServiceProvider.php or if you have any other custom Provider class, go to the boot method

utility macro implementation for laravel

now you can use in your blade view as Str::classNames([ …

🎈 Before finishing

This quick tip is heavily inspired by Alpine JS and a recent great pull request made to Laravel core framework where I found this technique.

very soon you’ll be able to write something similar for blade-x components in Laravel as the pull request got merged.

<div {{ $attributes->class(['p-4', 'bg-red' => $hasError]) }}>

πŸ‘‹ Thanks for stopping by πŸ˜‰ hope this helps …

--

--

Sourav Rakshit

πŸš΄β€β™‚οΈ an explorer πŸͺ writing programs ⌨ looking for cosmic secrets πŸŒ“