DEV Community

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

Posted on • Updated on

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.

Top comments (0)