Sling Academy
Home/PHP/Laravel: Displaying a default/placeholder value with Blade

Laravel: Displaying a default/placeholder value with Blade

Last updated: January 18, 2024

Introduction

Laravel’s Blade templating engine provides a convenient and elegant way to work with HTML templates in your Laravel applications. One of the handy features Blade offers is the ability to specify default or placeholder values for variables that may not always be set. In this tutorial, we’re going to explore different ways to display default values using Blade.

First, let’s get a brief overview of what Blade is and why it’s beneficial. Blade is Laravel’s built-in templating engine that allows you to create your view files. Blade templates are compiled into plain PHP code and cached until they’re modified, allowing for optimal performance. Blade also provides convenient short-cuts for common PHP functions and a very readable syntax, which greatly simplifies the process of writing dynamic web pages.

Basic Variable Output with Defaults

<h1>Hello, {{ $name ?? 'Guest' }}!</h1>

The syntax {{ $variable ?? 'default' }} is utilizing PHP’s null coalescing operator. This means that if $name is not set or is null, ‘Guest’ will be output by default.

Using the Blade @isset Directive

@isset($name)
    <h1>Hello, {{ $name }}!</h1>
    @else
    <h1>Hello, Guest!</h1>
@endisset

The @isset directive checks if a variable is set and displays its content if true; otherwise, it falls back to the @else portion.

Utilizing the @empty Directive for Placeholder

@empty($name)
    <h1>Hello, Guest!</h1>
    @else
    <h1>Hello, {{ $name }}!</h1>
@endempty

Conversely, the @empty directive checks if a variable is ’empty’. If a variable is considered ’empty’ in PHP (e.g., an empty string, null, false, an empty array), the code within the @empty block will be executed.

Default Value for Input Fields

<input type="text" name="username" value="{{ old('username', 'Guest') }}" />

This example demonstrates using the old() helper function with a default value. If the old value is not available (which means the form hasn’t been submitted yet or has been submitted without that field), it will display ‘Guest’ as the default placeholder.

Default Text in Case of a Null Relationship

<div>
    {{ $user->profile->bio ?? 'No biography provided.' }}
</div>

This snippet takes advantage of the null coalescing operator to provide default text in case a user’s profile relationship returns null. It’s a clean and simple way to handle potentially missing related models.

Using Blade Components for Reusable Defaults

@component('components.welcome', ['name' => $name])
    @slot('default')
        Guest
    @endslot
@endcomponent

If you’re using components in Blade, you can manage defaults using slots. Slots can hold default content which gets displayed only if the corresponding variable is null or not passed to the component.

In Conclusion

Laravel’s Blade templating engine simplifies tasks like setting default values in your view. Whether you’re displaying a simple ‘Guest’ placeholder when a user is not logged in, ensuring form input fields have a fallback value, or handling absent relationships, Blade’s syntax is clean and expressive. Remember to always validate and escape your data to maintain security and consistency of your application. With Blade’s convenience methods and easy-to-read syntax, you’re well prepared to deliver a polished user experience while keeping your templates as clear and maintainable as possible.

Next Article: Laravel Blade: Using ‘@yield’ and ‘@section’ directives

Previous Article: Laravel: How to generate raw HTML string from Blade template

Series: Laravel & Eloquent Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array