Laravel: How to Conditionally Display an Image with Blade

Updated: January 15, 2024 By: Guest Contributor Post a comment

Overview

Laravel’s templating engine Blade offers an elegant syntax for the various tasks a developer does regularly. One such task may involve deciding when and how to present images within a view based on certain conditions. This tutorial provides a step-by-step guide on how to conditionally display an image in Laravel using Blade.

Before we start, you should have Laravel installed on your local development machine and be familiar with the basics of Blade templates and Laravel syntax.

Understanding Blade Basics

Blade is a powerful templating engine in Laravel that allows for clean and straightforward templating. It extends PHP’s syntax to simplify certain tasks. One of its features is conditional statements that resemble regular PHP conditionals but are designed for simplicity and readability.

Basic Conditional Image Display

Let’s create a basic example to show or hide an image based on a variable from the controller.

@php
$showImage = true;
@endphp
<div>
    @if($showImage)
        <img src="/path/to/image.jpg" alt="Conditional Image"/>
    @endif
</div>

In the above example, an image will be displayed only if $showImage is true. This variable should typically be passed from the controller to the view.

Conditional Display Based on Data

Sometimes, we want to show an image that is relevant to the user or specific data. For instance, displaying user avatars conditionally:

<div>
    @isset($user->avatar)
        <img src="{{ $user->avatar }}" alt="{{ $user->name }}'s Avatar"/>
    @else
        <img src="/path/to/default/avatar.jpg" alt="Default Avatar"/>
    @endisset
</div>

Here, if the $user object has an avatar property, its value is used for the image source; otherwise, a default avatar image is shown.

Using the @empty Directive

Similar to @isset, the @empty directive can check if a variable is ’empty’. The following example demonstrates its use:

<div>
    @empty($profile->photo)
        <span>No photo available</span>
    @else
        <img src="{{ $profile->photo }}" alt="Profile Photo"/>
    @endempty
</div>

Note that the @empty block will be executed if $profile->photo is an empty string, null, or doesn’t exist.

Advanced Conditional Display

Let’s look at a more advanced scenario where an image needs to be displayed based on multiple conditions:

<div>
    @unless(Auth::guest())
        @can('view-profile-photo', $user)
            <img src="{{ $user->profile_photo }}" alt="Profile Photo"/>
        @else
            <!-- alternative content for users without the permission -->
        @endcan
    @endunless
</div>

This block combines multiple Blade directives to ensure that a profile photo is displayed only if the viewer is logged in and has the ‘view-profile-photo’ permission for the particular user.

Conditional Class Injection

To add additional complexity to your layouts, you may want to toggle CSS classes based on certain conditions. The following snippet demonstrates injecting a class conditionally:

<img src="{{ $user->avatar }}" class="{{ $user->status == 'active' ? 'active-user' : 'inactive-user' }}" alt="User Avatar"/>

This ternary expression adds the class active-user when the user’s status is ‘active’ and inactive-user otherwise.

Digging Deeper: Directives and Components

Blade also allows for the creation of custom directives, and in complex apps, you may find yourself creating directive conditions for your images:

@directive('profilePhoto', 'photo', 'default')
    @empty($photo)
        <img src="{{ $default }}" alt="Default Profile Photo"/>
    @else
        <img src="{{ $photo }}" alt="Profile Photo"/>
    @endempty
@enddirective

You can also create a reusable component for displaying images. Building a Blade component can encapsulate all the logic for displaying different types of images based on conditions:

<x-image :src="$user->avatar" default="/img/default-avatar.png" />

This method encapsulates the logical conditions within your component, simplifying the primary Blade file and promoting reusability across your application.

Conclusion

Using Blade to conditionally display images offers a seamless way to integrate logical decisions in your view. With different directives and the ability to create custom directives or components, Blade gives you powerful tools to maintain a clean and maintainable codebase while providing an excellent user experience. Remember that Blade is not just for display logic; its real power is in its flexibility and extensibility – use it to its fullest potential to create intuitive and dynamic user interfaces in your Laravel applications.