Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

earnbyshare2016's avatar

fallback value for both empty and null

I am creating a switchable theme system with blades. With in the blades, I call $settings which get from database and view()->share() to blades. As the system will allow some third-party frontend developers to build their own theme, I would like to shorten the syntax as much as possible and hence make the documents easier to understand.

Most values are non-empty string but some are empty string, null and undefined.

$settings['default'] = "Default Values";
$settings['normal'] = 'Normal Values';

$settings['empty'] = '';
$settings ['null'] = null;
$settings['undefined'];

The followings are my approach, Lets say $settings['any] will possibly be any type of empty string, null or undefined variable:

//Method 1
{{ $settings['any'] ?? $settings['default'] }}  // cannot show fallback value if setting is empty string

//Method 2
{{ $settings['any'] ?: $settings['default'] }}  // cannot show  fallback value if setting is undefined

//Method 3
{{ !empty($settings['any']) ? $settings['any'] : $settings['default'] }} //little bit long

//Method 4: building a global helper
function settings($key , $fallback){
	$settings = Setting::where('key' , $key )->orWhere('key',$fallback)->pluck('value','key')->toArray();
	return !empty($settings['any']) ? $settings['any'] : $settings['default'];
}
// then call in blade
{{ settings('any', 'default') }}

//Method 5
{{ @$settings['any'] ?:  $settings['default'] }}

Is there any better way to use one same syntax for all setting value called in blade? I would like to show fallback for each setting value with the minial syntax. Method 5 seems have the shortest syntax but I am not sure if it will throw errors in some conditions. Please advise.

0 likes
3 replies
anilkumarthakur60's avatar

inside boot method of the app service provider

$ss=cache()->remember(
'ss',
3600,
fn()=>Setting::all()->keyBy('key')
);
View::share('ss',$ss);

inside blade file

{!! $ss['key']->value??'default value'!!}
newbie360's avatar

if i understand correctly...just like this ?

$setting = [
    'default' => 'Default Values',
    'normal' => 'Normal Values',
    'other' => 'Other Values',
][$setting ?? 'default'];

Please or to participate in this conversation.