DEV Community

Cover image for Simplify your Laravel & Blade ifs: @pro, @free and @guest
farez
farez

Posted on • Edited on

1

Simplify your Laravel & Blade ifs: @pro, @free and @guest

Custom if tags to clean up your Blade templates.

If you're building a SaaS, you'll eventually start accumulating a lot of if statements that display one version of content for pro users (your paying subscribers), your free uses (if you have a free tier), and your guest users (those not logged in).

You can use @if directives in your Blade templates for this, but eventually it starts getting ugly, especially if the conditions are long and complex.

    @if (auth()->user()->isProUser())
        <button>Click here</button>
    @endif

    @if (auth()->user()->isFreeUser())
        <button>Upgrade</button>
    @endif

    @guest
        <button>Sign up</button>
    @endif
Enter fullscreen mode Exit fullscreen mode

It'll be better if it can look like this instead.

    @pro
        <button>Click here</button>
    @endpro

    @free
        <button>Upgrade</button>
    @endfree

    @guest
        <button>Sign up</button>
    @endguest
Enter fullscreen mode Exit fullscreen mode

Well you can do that with Blade's custom if statements.

Just add the following to your AppServiceProvider's boot method:

    public function boot()
    {
        Blade::if('pro', function () {
            if (auth()->guest()) {
                return false;
            }
            return auth()->user()->isPro();
        });

        Blade::if('free', function () {
            if (auth()->guest()) {
                return false;
            }
            return auth()->user()->isOnFreeTier();
        });
    }
Enter fullscreen mode Exit fullscreen mode

More on growing my indie SaaS business at https://farez.substack.com.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay